假设您有一个"word1 word2 word3 word4"
形式的字符串。分割它的最简单方法是split[0] = "word1 word2"
和split[1] = "word3 word4"
?
编辑:澄清
我想分裂,而不是分开[0] =" word1",我有前两个单词(我同意它不清楚)和所有其他单词分裂[1] ,即在第二个空间
答案 0 :(得分:6)
我会使用String.substring(beginIndex,endIndex);和String.substring(beginIndex);
String a = "word1 word2 word3 word4";
int first = a.indexOf(" ");
int second = a.indexOf(" ", first + 1);
String b = a.substring(0,second);
String c = b.subString(second); // Only startindex, cuts at the end of the string
这将导致a =" word1 word2"和b =" word3 word4"
答案 1 :(得分:3)
你想成对地做这个吗?这是SO社区维基Extracting pairs of words using String.split()
提供的动态解决方案String input = "word1 word2 word3 word4";
String[] pairs = input.split("(?<!\\G\\w+)\\s");
System.out.println(Arrays.toString(pairs));
输出:
[word1 word2, word3 word4]
答案 2 :(得分:2)
String str = "word1 word2 word3 word4";
String subStr1 = str.substring(0,12);
String subStr2 = str.substring(12);
对于分裂位置来说,这是你最好的选择。如果你需要在第二次出现空格时进行拆分,那么for循环可能是更好的选择。
int count = 0;
int splitIndex;
for (int i = 0; i < str.length(); i++){
if(str.charAt(i) == " "){
count++;
}
if (count == 2){
splitIndex = i;
}
}
然后你会把它分成如上所述的子串。
答案 3 :(得分:1)
这应该做你想要达到的目标。
您可以使用String.split(" ");
拆分初始字符串中的空格。
然后从那里你说你想要split[0]
中的前两个单词所以我只是用一个简单的条件if(i==0 || i == 1) add it to split[0]
String word = "word1 word2 word3 word4";
String[] split = new String[2];
//Split the initial string on spaces which will give you an array of the words.
String[] wordSplit = word.split(" ");
//Foreach item wordSplit add it to either Split[0] or Split[1]
for (int i = 0; i < wordSplit.length(); i++) {
//Determine which position to add the string to
if (i == 0 || i == 1) split[0] += wordSplit[i] + " ";
else {
split[1] += wordSplit[i] + " ";
}
}
答案 4 :(得分:1)
如果您希望将字符串拆分为两个单词的集合,则此代码可以提供帮助:
String toBeSplit = "word1 word2 word3 word4";
String firstSplit = a.substr(0,tBS.indexOf(" ", tBS.indexOf(" ")));
String secondSplit = firstSplit.substr(tBS.indexOf(" ", tBS.indexOf(" ")));
答案 5 :(得分:0)
通过公共分隔符(在本例中为空格)拆分字符串,并在输出中有条件地重新添加选择的分隔符,迭代2
string original = "word1 word2 word3 word4";
string[] delimitedSplit = original.split(" ");
for (int i = 0; i< delimitedSplit.length; i+=2) {
if (i < delimitedSplit.length - 1 ) { //handle uneven pairs
out.println(delimitedSplit[i] + " " + delimitedSplit[i+1] );
}
else {
out.println(delimitedSplit[i]
}