2012-05-25 50 views
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

+0

然后你可以将单词转换为字符数组,然后获取长度? –

回答

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 
3

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

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

words[i].length() 

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

2

第一:

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

,因为你进入for只有i不如这将做什么0

然后:

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

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

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

1

为了更好performaces而不是使用String.split(),这里一个例子的StringTokenizer:

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()); 
相关问题