user3789200
user3789200

Reputation: 1186

Giving a wrong count for a data read from a file

I was trying reading and writing some data from a file and counting very simple features from the written data such as number of spaces etc. using the split() method. Here is what I tried.

    File file=new File("G:\\AAA.txt");

    FileWriter fw=new FileWriter(file);

    fw.write("AAAAAAAA");

    fw.flush();
    fw.close();

    FileReader fr=new FileReader(file);

    String spaces="\\s";

    BufferedReader br=new BufferedReader(fr);

    String data=br.readLine();
    System.out.println(data);

    String[] tokenize=data.split(spaces);
    System.out.println(tokenize.length);

My problem is if there are no spaces I am getting the answer as 1 though it must be 0. when I was given 1 space it prints as 2. The answer is always larger than 1 from the given spaces.

Could someone please explain me the reason for not getting the exact answer.

Upvotes: 1

Views: 71

Answers (2)

Siva Kumar
Siva Kumar

Reputation: 2006

Why one if no space

If there is no string matched in split(#regex) , it will return input string into array of string.

Why always more than one if Space

It will split string by space , so first and second half will be there in array. So Length is greater than one.

Finding Count of Space

Pattern pattern = Pattern.compile("\\s");

Matcher matcher = pattern.matcher("AA   A");

int count = 0;
while (matcher.find())
    count++;

Upvotes: 1

Jeff Storey
Jeff Storey

Reputation: 57192

From the docs of String.split

If the expression does not match any part of the input then the resulting array has just one element, namely this string.

So with no spaces, the original string will be returned, thus the length of 1.

If you have one space, say "AAA AAA", the array will have two elements "AAA" and "AAA". So the length will always be one greater than the number of tokens.

Upvotes: 2

Related Questions