0

I'm trying to read a file and store the words from the file into a string array excluding spaces/multiple spaces. E.g. my file has the words "this is a test", the program should store into an array arr ["this","is","a","test"] and also increment a variable called wordCount every time it stores a word into the array.

I understand that i can use

fileContents.split("\\s+")

but that does not increment wordCount each time it adds a word into the array. I'm thinking a for loop will do the job but i don't know how.

Any help is appreciated. Thanks.

2 Answers 2

1

You can iterate the result of the split call and add one to the word count in the same iteration:

        String fileContents = "this is a test";
        int wordCount = 0;
        for (String word: fileContents.split("\\s+")) {
            System.out.println(word);
            wordCount++;
            System.out.println(wordCount);
        }

You should add the storage in the array structure each time you have a new word.

Sign up to request clarification or add additional context in comments.

Comments

0
BufferedReader reader;
    try {
        reader = new BufferedReader(new FileReader(
                "/Users/pankaj/Downloads/myfile.txt"));
        String line = reader.readLine();
        int count = 0;
        while (line != null) {
            String[] array = line.split("\\s+");
            count = count + array.length;
            line = reader.readLine();
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

Here I get the line by line so you can add additional functionality per line. Also get the count by count variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.