如何检查字符是否为空格?

时间:2016-09-20 23:25:40

标签: java

我正在尝试将字符串" "拆分为3个' '字符, 但是当我尝试检查if( curr_char == ' ')if Character.isWhitespace(curr-char)时,它不会将curr_char读为''。如果角色检测到的是空格,则应打印:

  

白色空间
   白色空间
   白色空间

但事实并非如此。

package LexAnalyzer;

import java.util.ArrayList;

public class LexAnalyzer {

    private String s;
    private char curr_char;
    private int i;  

    public LexAnalyzer(String s) {
        this.s = s;
        curr_char = s.charAt(0);
    }

    public void printTokenList() {
        while (i < s.length()) {
            //if the curr_char points somewhere in a string, keep go
            print_next_token();
        }
    }

    public void print_next_token() {

        if (i != 0) {
            curr_char = s.charAt(i);
        }

        //print "white space" if curr_char is whiteSpace
        if ( curr_char == ' ' || Character.isWhitespace(curr_char)) {
            System.out.printf("%s\n", " white space");
        }

        i++;
    }

    public static void main(String[] args) {
        ArrayList<String> input = new ArrayList<>();
        input.add("   ");

        for (int i = 0; i < input.size(); i++) {
            System.out.println("");
            System.out.println("TEST CASE: "+ (i+1));
            System.out.println("Input String: " + input.get(i));
            System.out.println("");
            LexAnalyzer lex = new LexAnalyzer(input.get(i));
            System.out.println("Token List: ");
            lex.printTokenList();
        }
    }
}

0 个答案:

没有答案