[英]How to split a String disregarding spaces?
I am trying to split this String: "send#hi how are you"
into 我正在尝试将此字符串拆分为
"send#hi how are you"
send
hi how are you
and then split "hi how are you"
into 然后将
"hi how are you"
分成
hi
how
are
you
My attempt: 我的尝试:
text[0] = "send#hi how are you";
String[] one = text[0].split("#");
String[] two = text[0].split("#")[1].split("\\s#");
When splitting "send#hi how are you"
, it only gives me "send" and "hi"... 拆分
"send#hi how are you"
,它只会给我“发送”和“嗨” ...
How can I change my code so it works? 如何更改我的代码使其起作用?
Here's code that should work, assuming that you don't want the word before the pound symbol: 假设您不希望在井号符号前使用该单词,那么下面的代码应该可以工作:
String x = "send#hi how are you";
x = x.substring(x.indexOf("#")+1, x.length());
String[] splitUp = x.split(" ");
If you do want both what's before and what's after the pound: 如果您确实想要英镑之前和之后的价格:
String x = "send#hi how are you";
String before = x.substring(0, x.charAt("#"));
String after = x.substring(x.charAt("#")+1, x.length());
String[] splitUp = after.split(" ");
And here's another way to do the second: 这是第二种方法:
String x = "send#hi how are you";
String[] pieces = x.split("#");
//at this point pieces[0] will be the word before the pound and pieces[1] what is after
String[] after = pieces[1].split(" ");
A final note - splitting on " "
is one way to do it, but splitting on "\\\\s"
is basically the same thing using regex, which may be more reliable. 最后一点-在
" "
上拆分是一种实现方式,但是在"\\\\s"
上拆分与使用正则表达式基本相同,这可能更可靠。
Your problem is that the text being split on (in this case "#"
) is consumed by the split - ie it's not retained in any of the resulting strings. 您的问题是拆分后的文本(在本例中为
"#"
)被拆分占用了,即,它不保留在任何结果字符串中。
The smallest edit to get you going is to change: 最小的修改方法就是更改:
String[] two = text[0].split("#")[1].split("\\s#");
to: 至:
String[] two = text[0].split("#")[1].split("\\s");
// ^--- remove the #
I would do it in this way: 我会这样:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String str = "send#hi how are you";
Pattern p = Pattern.compile("([^#]+)#(.*)");
Matcher m = p.matcher(str);
if (m.find()) {
String first = m.group(1);
String[] second = m.group(2).split("\\s+");
System.out.println(first);
System.out.println(java.util.Arrays.asList(second));
}
or if you want the simplest way: 或者,如果您想要最简单的方法:
String str = "send#hi how are you";
String[] parts = str.split("#", 2);
String first = parts[0];
String[] second = parts[1].split("\\s+");
System.out.println(first);
System.out.println(Arrays.asList(second));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.