简体   繁体   中英

How to split an entire sentence into characters in java?

I need to split:- "Hello World" into the following:

H

e

l

l

o

W

o

r

l

d

I have tried using .split(""). But after the space it is not working. How to split both strings?

Use StringName.toCharArray()

hope this might help you.

If you don't want the spaces, remove them before you split. And don't use split to get characters, better to get a character array directly:

s.replaceAll(" ", "").toCharArray()

If you don't even need a character array and you just want to print, then it's better to use streaming with a filter:

s.chars().filter(c -> c != ' ').forEach(c -> System.out.println((char)c))

Try this. Hope it works:

    String str = "Hello World";
    char [] ch = str.toCharArray();

    for( int i = 0; i < ch.length; i++ ) {
        if( ch[i] != ' ' ) { 
            System.out.println( ch[i] );
       }
    }

You can use String.toCharArry to convert a string into an array of characters:

String str = "Hello World";
char[] charArray = str.toCharArray();

If you want chars without space you can do the following

"Hello world".chars()
            .filter(e -> e != ' ')
            .forEach(e -> System.out.println((char)e));

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