计算特定字符(包括空格)之间的字符数

时间:2012-05-25 14:21:32

标签: java character

我有一个这种格式的文件:

City|the Location|the residence of the customer| the age of the customer| the first name of the customer|  

我只需要读取第一行,确定符号“|”之间有多少个字符。我需要代码来读取空格。

这是我的代码:

`FileInputStream fs = new FileInputStream("C:/test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
StringBuilder sb = new StringBuilder();

for(int i = 0; i < 0; i++){
br.readLine();
}
String line  = br.readLine();

System.out.println(line);

String[] words = line.split("|");
for (int i = 0; i < words.length; i++) {
    int counter = 0;
    if (words[i].length() >= 1) {
        for (int k = 0; k < words[i].length(); k++) {
            if (Character.isLetter(words[i].charAt(k)))
                counter++;
        }
        sb = new StringBuffer();
        sb.append(counter).append(" ");
    }
}
System.out.println(sb);
}

`

我是java的新手

4 个答案:

答案 0 :(得分:3)

  

我只需要读取第一行,确定符号“|”之间有多少个字符。我需要代码来读取空格。

String.split采用正则表达式,因此|需要进行转义。使用\\|然后

words[i].length()

将为您提供|符号之间的字符数。

答案 1 :(得分:2)

尝试这样的事情:

String line = "City|the Location|the residence of the customer| the age of the customer| the first name of the customer|";
String[] split = line.split("\\|"); //Note you need the \\ as an escape for the regex Match
for (int i = 0; i < split.length; i++) {
  System.out.println("length of " + i + " is " + split[i].length());
}

输出:

length of 0 is 4
length of 1 is 12
length of 2 is 29
length of 3 is 24
length of 4 is 31

答案 2 :(得分:2)

第一:

for(int i = 0; i < 0; i++){
  br.readLine();
}

只有当for低于0

时输入i才会执行此操作

然后:

if (words[i].length() >= 1) { 

if不是很有用,因为如果for为0,则不会输入下一个words[i].length()

最后,如果不对其进行测试,您可能需要测试该字符是否为空格 OR words[i].charAt(k).equals(" ")

答案 3 :(得分:1)

为了获得更好的性能,请使用StringTokenizer而不是String.split(),这里有一个例子:

FileInputStream fs = new FileInputStream("C:/test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
StringBuilder sb = new StringBuilder();

String line  = br.readLine();

System.out.println(line);

StringTokenizer tokenizer = new StringTokenizer(line, "|");
while (tokenizer.hasMoreTokens()) {
    String token = tokenizer.nextToken();
    sb.append(token.length()).append(" "); 
}
System.out.println(sb.toString());