簡體   English   中英

在java中的特定位置拆分字符串

[英]Splitting a string at a particular position in java

假設您有一個"word1 word2 word3 word4"形式的字符串。 拆分它的最簡單方法是split[0] = "word1 word2"split[1] = "word3 word4"

編輯:澄清

我想拆分,而不是拆分[0] =“word1”,我有前兩個單詞(我同意它不清楚)和所有其他單詞在split [1],即在第二個空格

我會使用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”

你想成對做這個嗎? 這是SO社區wiki提供的動態解決方案, 使用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]
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM