假设您有一个形如"word1 word2 word3 word4"的字符串。最简单的一种方式是如何拆分它,使得split[0] = "word1 word2",并且split[1] = "word3 word4"?
编辑:澄清
我想要拆分的方式是将第一个空格之前的两个单词(我同意不太清楚),和所有其他单词在第二个空格上分开。
编辑:澄清
我想要拆分的方式是将第一个空格之前的两个单词(我同意不太清楚),和所有其他单词在第二个空格上分开。
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
你总是想要成对进行吗?这是SO社区维基提供的一种动态解决方案,使用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]
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;
}
}
然后您将像上面那样将其拆分为子字符串。
这应该可以实现你想要达到的目标。
您可以使用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] + " ";
}
}
String toBeSplit = "word1 word2 word3 word4";
String firstSplit = a.substr(0,tBS.indexOf(" ", tBS.indexOf(" ")));
String secondSplit = firstSplit.substr(tBS.indexOf(" ", tBS.indexOf(" ")));
按其常见分隔符(在此情况下为空格)拆分字符串,并有条件地在输出中重新添加所选的分隔符,每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]
}