如何将Java字符串放入数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18863882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:43:51  来源:igfitidea点击:

How to put Java String to array

javaarraysstring

提问by koli

I have a java String of a list of numbers with comma separated and i want to put this into an array only the numbers. How can i achieve this?

我有一个用逗号分隔的数字列表的java字符串,我想将它放入一个只有数字的数组中。我怎样才能做到这一点?

String result=",17,18,19,";

采纳答案by tskuzzy

First remove leading commas:

首先删除前导逗号:

result = result.replaceFirst("^,", "");

If you don't do the above step, then you will end up with leading empty elements of your array. Lastly split the String by commas (note, this will not result in any trailingempty elements):

如果您不执行上述步骤,那么您最终将得到数组的前导空元素。最后用逗号分割字符串(注意,这不会导致任何尾随空元素):

String[] arr = result.split(",");

One liner:

一个班轮:

String[] arr = result.replaceFirst("^,", "").split(",");

回答by Kon

String[] myArray = result.split(",");

This returns an array seperated by your argument value, which can be a regular expression.

这将返回一个由您的参数值分隔的数组,它可以是一个正则表达式。

回答by Suresh Atta

Try split()

尝试 split()

Assuming this as a fixed format,

假设这是一个固定格式,

String result=",17,18,19,";
String[] resultarray= result.substring(1,result.length()).split(",");
for (String string : resultarray) {
    System.out.println(string);
}

//output : 17 18 19

That split() methodreturns

也就是说split()方法返回

the array of strings computed by splitting this string around matches of the given regular expression

通过围绕给定正则表达式的匹配拆分此字符串计算出的字符串数组

回答by Vimal Bera

You can do like this :

你可以这样做:

String result ="1,2,3,4";
String[] nums = result.spilt(","); // num[0]=1 , num[1] = 2 and so on..

回答by rickygrimes

String result=",17,18,19,";
String[] resultArray = result.split(",");
System.out.printf("Elements in the array are: ");
    for(String resultArr:resultArray)
    {
        System.out.println(resultArr);
    }