Hi all,

I am trying to take a list of words (from a text file) and then split each word into characters how can I do this?

The code I currently have just reads in all the words (at, as, ate, apple, apply) found in text file and prints them out (as many times as the length of the word). What I really want is for my program to take one word from the text file and split it into characters on one line in the output. Would I have to save the words from the text file in an array first?

My code:

import java.io.*;


class FileReadTest {


public static void main (String[] args) {
FileReadTest t = new FileReadTest(); //creates object of the class
t.readMyFile(); //applies the readMyFile method to the object
}


void readMyFile() {
String record = null;  //initialises the string variable record to null


try {
FileReader fr = new FileReader("C:\\Documents and Settings\\sumiya\\My Documents\\Scrabble Project\\scrabbledict.txt");
//creates a new filereader for the named file in the arguments
BufferedReader br = new BufferedReader(fr);


record = new String();
while ((record = br.readLine()) != null) {
System.out.println(record);


for(int i=0; i<record.length(); i++){
record.charAt(i);
System.out.println("Character at i = " +record);
}


}
} catch (IOException e) {
// catches possible io errors from readLine()
System.out.println("Uh oh, got an IOException error!");
e.printStackTrace();
}
}


} // end of class

Dani AI

Generated

The observed behavior comes from printing the whole line (record) inside the character loop instead of the character at index i. That makes each word appear as many times as its length. It isn’t necessary to store all words in an array first — each word can be processed as it’s read. ’s file can be handled line-by-line and tokenized into words (one word per line or several per line), then each word split into chars and printed on a single output line.

A simple, safe approach (handles one-or-more words per line) — read a line, split on whitespace, then build a single-line string of characters for each word:

import java.io.*;

public class SplitWords {
    public static void main(String[] args) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader("scrabbledict.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                for (String word : line.trim().split("\\s+")) {
                    if (word.isEmpty()) continue;
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < word.length(); i++) {
                        if (i > 0) sb.append(' ');
                        sb.append(word.charAt(i));
                    }
                    System.out.println(sb.toString()); // prints: a t  (for "at")
                }
            }
        }
    }
}

Alternatives and notes: word.toCharArray() yields a char[] if that’s preferred. StringTokenizer (mentioned by ) works but String.split("\\s+") or Scanner are more modern. On ’s point about declaration, String record = null; is valid — strings are immutable, but the variable can be reassigned. Troubleshooting tips: verify that the loop prints record.charAt(i) (or uses sb.append(word.charAt(i))) rather than record; trim lines and skip empty tokens; if the input may contain punctuation, sanitize with word = word.replaceAll("\\W+", "") before splitting. For full Unicode code points (rare in plain English word lists), iterate word.codePoints() instead of charAt.

Recommended Answers

All 2 Replies

You could use a StringTokenizer to read everything that's a word(doesn't read white space).
Get the length of the word.
In a for loop you can process the char at index 'i' by using charAt(i).

String record = null;

I'd recommend changing that to String record; . Once you create a String, even if it's null, you can't change it - they're immutable. String record; will tell the app that a String called record will be created, but not actually create it until you do record = something .

As for your actual question:

What I really want is for my program to take one word from the text file and split it into characters on one line in the output.

String.toCharArray(); ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.