read in the single bytes and check if the current byte is a word separator / a space char.
count these separators and finally add 1.
FileInputStream in = new FileInputStream("words.txt");
byte current_byte;
byte separator = " ".getBytes()[0];
int gap_counter = 0;
while((current_byte = in.read()) != -1) {
if(current_byte.equals(separator)) {
gap_counter++;
}
}
System.out.println((gap_counter+1) + " words found in file words.txt");
to make sure that there are no multiple separators ("word1 word2 word3 word4 word5") you might first read in the whole file and use a StringTokenizer to get the number of words:
FileInputStream in = new FileInputStream("words.txt");
byte current_byte;
String whole_file_text = new String();
while((current_byte = in.read()) != -1) {
whole_file_text += current_byte;
}
StringTokenizer tokenizer = new StringTokenizer(whole_file_text, " ");
System.out.println(tokenizer.countTokens() + " words found in file words.txt");
First read the info from file. One way ....
String str;
try
{
DataInputStream in = new DataInputStream(new FileInputStream("1.txt"));
while((str=in.readLine())!=null)
{
System.out.println(str);
}
}catch(FileNotFoundException e){}
catch(EOFException e){}
catch(IOException e){}
if you just need to count words in the string (assuming space delimitation), easiest way to count words is this.......
StringTokenizer st = new StringTokenizer(yourString);
st.countTokens() should return thenumber of words in the string.
If however, the delimiter is not space, use this approach....
int index=0;
int numOccurrences=0;
while(true)
{
index= str.indexOf("if",index);
System.out.println("index is.."+index);
if(index==-1) break;
numOccurrences++;
index++;
}
System.out.println("Num ..."+numOccurrences);
Rishi