如何翻轉字串的每個其他單詞?例如,為了簡化,我想把:
"Hello World Hello World Hello World"變成"World Hello World Hello World Hello"
我嘗試變成一個串列,以便更容易訪問每個單詞,其中:String[] temp = pattern.split(str);
并嘗試:
int oddInd = 1;
int evenInd = 0;
while (true) {
while (evenInd < temp.length && temp[evenInd] % 2 == 0)
evenInd = 2;
while (oddInd < temp.length && temp[oddInd] % 2 == 1)
oddInd = 2;
if (evenInd < temp.length && oddInd < temp.length) {
int tt = arr[evenInd];
temp[evenInd] = temp[oddInd];
temp[oddInd] = tt;
else
break;
但它似乎不起作用,因為我處理的是字串而不是整數。我也嘗試了一些更簡單的方法,例如,但它也不起作用。
for (int i = 1; i < temp.length; i =2) {
if(i % 2 == 1) {
temp[i] = temp[i-1];
} else {
temp[i] = temp[i 1];
}
result = temp[i];
uj5u.com熱心網友回復:
您可以只遍歷偶數索引(增加 2),然后您就知道其他所有索引都是奇數:
String result = "";
for (int even = 0; even < temp.length; even = 2) {
int odd = even 1;
if (odd < temp.length) {
result = temp[odd] " ";
}
result = temp[even] " ";
}
result = result.trim();
uj5u.com熱心網友回復:
您可以嘗試以下方法,其邏輯如下:
方法在這里:
我已經通過空間溢位了給定的字串,然后以 2 的索引增量迭代創建的陣列,即i 2檢查是否i 1超出陣列的范圍。如果不是,則交換其他值,否則對陣列不執行任何操作,如下所示:
public class Test {
public static void main(String[] args) {
String s = "Hello World Hello World Hello World";
String[] strArray = s.split(" ");//Creating a string array by splitting the given string with space
for(int i = 0; i < strArray.length;i = i 2){//Iterating the string array and increasing the index by 2
if(i 1 < strArray.length){// checking the value i 1 should be less than length of the array , do nothing if it fails
//swapping Logic
String temp1 = strArray[i];
String temp2 = strArray[i 1];
strArray[i 1] = temp1;
strArray[i] = temp2;
//swapping Logic
}
}
for(String str: strArray){
System.out.print(str " ");
}
}
}
輸出:
Input:: Hello World Hello World Hello World
Output:: World Hello World Hello World Hello
Input:: Hello World Hello World Hello
Output:: World Hello World Hello Hello
uj5u.com熱心網友回復:
拆分然后通過 2 的交換元素進行迭代,然后加入:
String [] words = str.split(" ");
for (int i = 0; i < words.length; i =2) {
String tmp = words[i];
words[i] = words[i 1];
words[j] = tmp;
}
String result = String.join(tmp, " ");
uj5u.com熱心網友回復:
您可以在拆分字串陣列索引的 Intstream 中使用簡單的模運算來翻轉奇偶序列并重新加入..
String sample = "Hello World Hello World Hello World";
String[] splits = sample.split("\\s ");
String flipped = IntStream.range(0, splits.length)
.map(i -> (i 1) % 2)
.mapToObj(i -> splits[i])
.collect(Collectors.joining(" "));
System.out.println("flipped:-> " flipped);
印刷
翻轉:-> World Hello World Hello World Hello
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516507.html
標籤:爪哇细绳索引交换
上一篇:大寫第一個字母,但不是當數字在Python中排在第一位時
下一篇:Python字串長度生成輸出
