Java 拆分字符串并添加到字符数组?
例如,我的程序有以下字符串输入:Java 拆分字符串并添加到字符数组?,java,arrays,string,char,Java,Arrays,String,Char,例如,我的程序有以下字符串输入: "stringToRemoveCharsFrom, f d s a" 我想将字符串拆分为以下两个字符串: 1. the string before the comma - i.e. stringToRemoveCharsFrom 2. the string after the comma - i.e. f d s a 我知道我可以使用.split方法并添加到array/arraylist 但是,如何确定逗号前的字符串和逗号后的字符串 也就是说,我想从第二个f
"stringToRemoveCharsFrom, f d s a"
我想将字符串拆分为以下两个字符串:
1. the string before the comma - i.e. stringToRemoveCharsFrom
2. the string after the comma - i.e. f d s a
我知道我可以使用.split方法并添加到array/arraylist
但是,如何确定逗号前的字符串和逗号后的字符串
也就是说,我想从第二个f d s a字符串创建一个char数组,但是如何确定从这两个字符串中的哪一个创建数组 逗号前的第一个字符串将位于split返回的数组的第一个索引处,例如0。逗号后的字符串将位于第二个索引处,例如1。大概
String str = "stringToRemoveCharsFrom, f d s a";
String[] tokens = str.split("\\s*,\\s*");
System.out.println("left = " + tokens[0]);
String[] charTokens = tokens[1].split("\\s+");
System.out.println("right = " + Arrays.toString(charTokens));
哪个输出
left = stringToRemoveCharsFrom
right = [f, d, s, a]
数组中的第一个是逗号之前的一个
String[] vals = str.split(",");
System.out.println(vals[0]); // first part
System.out.println(vals[1]); // second part.
char[] s = vals[1].toCharArray(); // your character array.
System.out.println(Arrays.toString(s));
// or if you want an array of single char strings.
String[] st = vals[1].split("");
System.out.println(Arrays.toString(st));
如果您不希望,数组中将包含空格字符
您可以执行以下操作
弦
String[] charsNoSpaces = vals[1].trim().split("\\s+");
System.out.println(Arrays.toString(charsNoSpaces));
查尔斯
String[] charsNoSpaces = vals[1].trim().split("\\s+");
System.out.println(Arrays.toString(charsNoSpaces));
char[] charsNoSpaces2 = vals[1].replaceAll("\\s+","").toCharArray();
System.out.println(Arrays.toString(charsNoSpaces2));