java中字符串到字符串数组的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3413586/
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
string to string array conversion in java
提问by riyana
I have a string="name";
I want to convert into a string array.
How do I do it?
Is there any java built in function? Manually I can do it but I'm searching for a java built in function.
我有一个string="name";
我想转换成字符串数组。我该怎么做?有没有内置的java函数?手动我可以做到,但我正在寻找一个java内置函数。
I want an array where each character of the string will be a string. like char 'n' will be now string "n" stored in an array.
我想要一个数组,其中字符串的每个字符都是一个字符串。像 char 'n' 现在将是存储在数组中的字符串“n”。
采纳答案by rsp
To start you off on your assignment, String.split
splits strings on a regular expression, this expression may be an empty string:
为了开始你的任务,String.split
在正则表达式上拆分字符串,这个表达式可能是一个空字符串:
String[] ary = "abc".split("");
Yields the array:
产生数组:
(java.lang.String[]) [, a, b, c]
Getting rid of the empty 1st entry is left as an exercise for the reader :-)
摆脱空的第一个条目留给读者练习:-)
Note:In Java 8, the empty first element is no longer included.
注意:在 Java 8 中,不再包含空的第一个元素。
回答by Aidanc
回答by thelost
String array = array of characters ?
字符串数组 = 字符数组?
Or do you have a string with multiple words each of which should be an array element ?
或者你有一个包含多个单词的字符串,每个单词都应该是一个数组元素?
String[] array = yourString.split(wordSeparator);
String[] array = yourString.split(wordSeparator);
回答by f1sh
String strName = "name";
String[] strArray = new String[] {strName};
System.out.println(strArray[0]); //prints "name"
The second line allocates a String array with the length of 1. Note that you don't need to specify a length yourself, such as:
第二行分配一个长度为1的String数组,注意不需要自己指定长度,比如:
String[] strArray = new String[1];
instead, the length is determined by the number of elements in the initalizer. Using
相反,长度由初始化器中的元素数量决定。使用
String[] strArray = new String[] {strName, "name1", "name2"};
creates an array with a length of 3.
创建一个长度为 3 的数组。
回答by Landei
I guess there is simply no need for it, as it won't get more simple than
我想根本不需要它,因为它不会比
String[] array = {"name"};
Of course if you insist, you could write:
当然,如果你坚持,你可以写:
static String[] convert(String... array) {
return array;
}
String[] array = convert("name","age","hobby");
[Edit] If you want single-letter Strings, you can use:
[编辑] 如果你想要单字母字符串,你可以使用:
String[] s = "name".split("");
Unfortunately s[0] will be empty, but after this the letters n,a,m,e will follow. If this is a problem, you can use e.g. System.arrayCopy in order to get rid of the first array entry.
不幸的是 s[0] 将是空的,但在此之后字母 n,a,m,e 将跟随。如果这是一个问题,您可以使用例如 System.arrayCopy 来删除第一个数组条目。
回答by finnw
Assuming you really want an array of single-character strings (not a char[]
or Character[]
)
假设您真的想要一个单字符串数组(不是 achar[]
或Character[]
)
1. Using a regex:
1. 使用正则表达式:
public static String[] singleChars(String s) {
return s.split("(?!^)");
}
The zero width negative lookahead prevents the pattern matching at the start of the input, so you don't get a leading empty string.
零宽度负前瞻可防止输入开始时的模式匹配,因此您不会得到前导空字符串。
2. Using Guava:
2. 使用番石榴:
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.google.common.primitives.Chars;
// ...
public static String[] singleChars(String s) {
return
Lists.transform(Chars.asList(s.toCharArray()),
Functions.toStringFunction())
.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
回答by atamanroman
String data = "abc";
String[] arr = explode(data);
public String[] explode(String s) {
String[] arr = new String[s.length];
for(int i = 0; i < s.length; i++)
{
arr[i] = String.valueOf(s.charAt(i));
}
return arr;
}
回答by Frank Hou
/**
* <pre>
* MyUtils.splitString2SingleAlphaArray(null, "") = null
* MyUtils.splitString2SingleAlphaArray("momdad", "") = [m,o,m,d,a,d]
* </pre>
* @param str the String to parse, may be null
* @return an array of parsed Strings, {@code null} if null String input
*/
public static String[] splitString2SingleAlphaArray(String s){
if (s == null )
return null;
char[] c = s.toCharArray();
String[] sArray = new String[c.length];
for (int i = 0; i < c.length; i++) {
sArray[i] = String.valueOf(c[i]);
}
return sArray;
}
Method String.split
will generate empty 1st, you have to remove it from the array. It's boring.
方法String.split
将生成空的 1st,您必须将其从数组中删除。这很无聊。
回答by HyperNeutrino
You could use string.chars().mapToObj(e -> new String(new char[] {e}));
, though this is quite lengthy and only works with java 8. Here are a few more methods:
您可以使用string.chars().mapToObj(e -> new String(new char[] {e}));
,尽管这很冗长并且仅适用于 java 8。这里还有一些方法:
string.split(""); (Has an extra whitespace character at the beginning of the array if used before Java 8)
string.split("|");
string.split("(?!^)");
Arrays.toString(string.toCharArray()).substring(1, string.length() * 3 + 1).split(", ");
string.split(""); (Has an extra whitespace character at the beginning of the array if used before Java 8)
string.split("|");
string.split("(?!^)");
Arrays.toString(string.toCharArray()).substring(1, string.length() * 3 + 1).split(", ");
The last one is just unnecessarily long, it's just for fun!
最后一个是不必要的长,只是为了好玩!
回答by AGéoCoder
An additional method:
一个额外的方法:
As was already mentioned, you could convert the original String "name" to a char array quite easily:
如前所述,您可以很容易地将原始字符串“名称”转换为字符数组:
String originalString = "name";
char[] charArray = originalString.toCharArray();
To continue this train of thought, you could then convert the char array to a String array:
为了继续这个思路,您可以将 char 数组转换为 String 数组:
String[] stringArray = new String[charArray.length];
for (int i = 0; i < charArray.length; i++){
stringArray[i] = String.valueOf(charArray[i]);
}
At this point, your stringArray will be filled with the original values from your original string "name". For example, now calling
此时,您的 stringArray 将填充您的原始字符串“name”中的原始值。例如,现在调用
System.out.println(stringArray[0]);
Will return the value "n" (as a String) in this case.
在这种情况下将返回值“n”(作为字符串)。