0

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

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

4 回答 4

3

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

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

words[i].length()

会给你符号之间的字符数|

于 2012-05-25T14:28:19.153 回答
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
于 2012-05-25T14:29:41.067 回答
2

第一的 :

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

这将无济于事,因为您输入foronly ifi低于 0

然后:

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

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

最后没有测试它,你可能想要测试字符是否是字母 words[i].charAt(k).equals(" ")空格似乎相当正确

于 2012-05-25T14:29:55.310 回答
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());
于 2012-05-25T14:40:07.863 回答