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();
}

が 0 より小さいfor場合にのみ入力するため、これは何もしません。i

それで:

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

が 0の場合は次を入力しないため、これifはあまり役に立ちません。forwords[i].length()

最後にそれをテストせずに、文字が文字または words[i].charAt(k).equals(" ")スペースの場合はテストしたいかもしれませんが、かなり正しいようです

于 2012-05-25T14:29:55.310 に答える
1

パフォーマンスを向上させるには、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());
于 2012-05-25T14:40:07.863 に答える