简体   繁体   中英

How do I split a String by Characters in Java?

I've tried numerous times with different regexes but none seem to work. Basically, I have a StringTokenizer that is currently splitting the string by spaces, but I want it to split by each character instead. My current code:

FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
StringTokenizer st = new StringTokenizer(br.readLine());
char c = reader.next().charAt(0);

This gets a string's character at index zero. Strings begin at index zero. Also, an alternative is

for (int i = 0; i < numberOfChars; ++i){
    // get the character using charAt(i)
    // store the character using an array, as others have specified
}

Remember to use new Scanner(BufferedReader(FileReader("test.txt")));

For more info, read Take a char input from the Scanner

I have a StringTokenizer that is currently splitting the string by spaces,

Read the StringTokenizer API. If you don't specify the delimiters, then the default delimeters are used.

So you need to specify all the delimeters.

Or, and easier approach is to just use the String.toCharArray() method and iterate through the array.

If you need them as chars:

char[] characters = br.readLine().toCharArray();

If you need them as Strings:

String[] characters = br.readLine().split("");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM