[英]How can I split a String of dots?
I have a String which looks like this "-..."
I would like to split it into 4 simple Strings "-"
"."
我有一个看起来像这样的字符串
"-..."
我想将其拆分为4个简单的字符串"-"
"."
"."
"."
How can I achieve this? 我该如何实现?
String.split(".")
and String.toCharArray()
did not work. String.split(".")
和String.toCharArray()
无效。
Split using the empty string as seperator: 使用空字符串作为分隔符进行拆分:
"-...".split("")
Unfortunately this adds a empty string as the first element in java 7. (In java 8 it works fine). 不幸的是,这将空字符串添加为Java 7中的第一个元素。(在Java 8中,它可以正常工作)。
Faraj Farook's solution works in java 7 and java 8. Faraj Farook的解决方案可在Java 7和Java 8中使用。
您可以使用一些不错的Java 8功能:
String[] foo = "-....".chars().mapToObj(String::new).toArray(String[]::new);
"-...".split("(?!^)");
This will simply give the array of string for all the characters. 这将简单地给出所有字符的字符串数组。 For example the above will give the array of:
例如,上面将给出以下数组:
String[] (length=4) ["-", ".", ".", "."]
you can convert charArray to string : 您可以将charArray转换为string:
String string="-...";
char[] chars = string.toCharArray();
List<String> stringList = new ArrayList<>();
for (char stringChar : chars) {
stringList.add(String.valueOf(stringChar));
}
Use "-...".ToCharArray()
as it's working perfectly on my computer. 使用
"-...".ToCharArray()
因为它在我的计算机上运行良好。 You might need to use "-...".ToCharArray()
instead of "-...".toCharArray()
. 您可能需要使用
"-...".ToCharArray()
而不是"-...".toCharArray()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.