Reputation: 4150
I have a File that is in this format:
City|the Location|the residence of the customer| the age of the customer| the first name of the customer|
I need to read just the first line an determine how many characters are between the sign "|". I need the code to read even the spaces.
This is the code I have:
`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);
}
`
I am very new to java
Upvotes: 0
Views: 1292
Reputation: 1312
For better performaces use StringTokenizer instead of String.split(), here an example:
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());
Upvotes: 1
Reputation: 10304
First :
for(int i = 0; i < 0; i++){
br.readLine();
}
This will do nothing since you enter the for
only if i
is inferior to 0
Then:
if (words[i].length() >= 1) {
This if
is not very useful since you won't enter the next for
if words[i].length()
is 0
Finally without testing it, it seems rather correct you may want to test if the character is a letter OR words[i].charAt(k).equals(" ")
for spaces
Upvotes: 2
Reputation: 29071
Try something like this:
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());
}
The output:
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
Upvotes: 2
Reputation: 421150
I need to read just the first line an determine how many characters are between the sign "|". I need the code to read even the spaces.
String.split
takes a regular expression, so |
needs to be escaped. Use \\|
and then
words[i].length()
will give you the number of characters between the |
symbols.
Upvotes: 3