简体   繁体   English

如何在Java中将整个句子拆分为字符?

[英]How to split an entire sentence into characters in java?

I need to split:- "Hello World" into the following: 我需要拆分:-“ Hello World”分为以下几部分:

H

e

l

l

o

W

o

r

l

d

I have tried using .split(""). 我尝试使用.split(“”)。 But after the space it is not working. 但是经过空间后,它无法正常工作。 How to split both strings? 如何拆分两个字符串?

Use StringName.toCharArray() 使用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: 并且不要使用split来获取字符,最好直接获取一个字符数组:

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.toCharArry将字符串转换为字符数组:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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