从字符串中分割单个字符 [英] Split individual characters from a string

查看:60
本文介绍了从字符串中分割单个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写以下程序,以从字符串中分离字符并将其分配给数组.

I'm writing following program to separate characters from a string and assign it to an array.

public class Str {
    public static void main(String[] args) {
        String str = "hello";
        String[] chars = str.split("");
        for (int i = 0; i < chars.length; i++) {
            System.out.println(i + ":" + chars[i]);
        }
    }
}

我得到的输出是:

0:
1:h
2:e
3:l
4:l
5:o

我得到一个空字符串作为数组的第一个元素.我期望输出没有空字符串,而chars数组的长度是5而不是6.为什么拆分此String后会出现空char?

I'm getting an empty string as the first element of the array. I was expecting the output to be without empty string and the length of chars array to be 5 instead of 6. Why empty char is coming after splitting this String?

推荐答案

您可以使用

You can use String#toCharArray() method:

String str = "hello";
char[] arr = str.toCharArray();


关于您的问题,当您分割一个空字符串时,您将获得第一个元素为空字符串,因为您的字符串以一个空字符串开头,并且在每个字符之后也都有一个空字符串.


As for your question, when you split on an empty string, you will get the first element as empty string, because, your string starts with an empty string, and after every character also, there is an empty string.

因此,第一次拆分发生在第一个字符之前.

So, the first split occurs before the first character.

 h e l l o
^ ^ ^ ^ ^ ^
"Split location"

按照

因此,空字符串不包含在结果数组中.

Trailing empty strings are therefore not included in the resulting array.

这篇关于从字符串中分割单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆