在Java中按特定位置拆分字符串

5
假设您有一个形如"word1 word2 word3 word4"的字符串。最简单的一种方式是如何拆分它,使得split[0] = "word1 word2",并且split[1] = "word3 word4"?
编辑:澄清
我想要拆分的方式是将第一个空格之前的两个单词(我同意不太清楚),和所有其他单词在第二个空格上分开。

6
为什么要在那个位置?你的标题提到了“在特定位置”,但我们不知道这个位置是指字符索引还是其他什么。 - Jon Skeet
3
如果您想将每一对单词放入一个字符串中,最简单的方法是通过空格分割所有单词,然后遍历并连接每一对单词。 - colti
你需要更多具体的说明,你到底想要什么。你想在中间分割,还是按照任意索引或其他规则?你想要分割后只有两个项目,还是根据某个规则有更多项目? - MrJman006
抱歉造成困惑,我澄清了问题。 - giulio
显示剩余2条评论
6个回答

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"。

我更新了代码以查找第二个空格“ ”的出现。这是假设您的单词由空格分隔的情况下。 - Einar Sundgren
我认为第二个索引应该从第一个索引加1开始,而不是从第一个索引开始。 - giulio

3

你总是想要成对进行吗?这是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]

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;
    }
}

然后您将像上面那样将其拆分为子字符串。


1
我建议使用 String.indexOf("foo");。 - Einar Sundgren
String.indexOf("foo") 只返回字符的第一个出现位置。你需要像 String.indexOf("foo", 5) 这样做,其中第二个参数是 indexOf() 开始搜索的索引。 - user4205830

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] + " ";
    }
}

0
如果您想将一个字符串分割成两个单词的组合,可以使用以下代码:
String toBeSplit = "word1 word2 word3 word4";
String firstSplit = a.substr(0,tBS.indexOf(" ", tBS.indexOf(" ")));
String secondSplit = firstSplit.substr(tBS.indexOf(" ", tBS.indexOf(" ")));

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]
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接