我設法拆分了字串,但是如何在字串的后半部分將 h 與 t 和 t 與 h 交換?
public class Tollring3 {
public static void main(String args[])
{
String base = "httthhhtth";
int half = base.length()/2;
// int half = base.length() % 2 == 0 ? base.length()/2 : base.length()/2 1;
String first = base.substring(0, half);
String second = base.substring(half);
System.out.println("Actual String :- " base);
System.out.println(first);
System.out.println(second);
char[] c = second.toCharArray();
// Replace with a "swap" function, if desired:
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
System.out.println(swappedString);
}
}
如何在字串的后半部分將 h 與 t 和 t 與 h 交換
uj5u.com熱心網友回復:
這個程式將一個字串分成兩半,然后交換后半的第一個和第二個字符。公共類 Tollring3 {
public static void main(String args[])
{
String base = "httthhhtth";
int half = base.length()/2;
// int half = base.length() % 2 == 0 ? base.length()/2 : base.length()/2 1;
String first = base.substring(0, half);
String second = base.substring(half);
System.out.println("Actual String :- " base);
System.out.println(first);
System.out.println(second);
char[] c = second.toCharArray();
// Replace with a "swap" function, if desired:
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
System.out.println(swappedString);
}
}
uj5u.com熱心網友回復:
您可以swap按如下方式定義函式:
String swap(String str) {
char[] arr = str.toCharArray();
char[] result = new char[arr.length];
for (int i = 0; i < arr.length; i )
result[i] = arr[i] == 'h' ? 't' : arr[i] == 't' ? 'h' : arr[i];
return new String(result);
}
在函式中,我們有
- 將給定的字串(后半部分)拆分為一個
char陣列,arr. - 創建了另一個相同大小的
char陣列result。 - 迭代
arr以存盤每個字符 fromarrintoresult同時交換h和t彼此。 - 終于回傳了一個新
String創建出來的result。
完整演示:
public class Main {
public static void main(String args[]) {
String base = "httthhhtth";
int half = base.length() / 2;
// int half = base.length() % 2 == 0 ? base.length()/2 : base.length()/2 1;
String first = base.substring(0, half);
String second = base.substring(half);
System.out.println("Actual String :- " base);
System.out.println(first);
System.out.println(second);
String swappedString = swap(second);
System.out.println(swappedString);
}
static String swap(String str) {
char[] arr = str.toCharArray();
char[] result = new char[arr.length];
for (int i = 0; i < arr.length; i )
result[i] = arr[i] == 'h' ? 't' : arr[i] == 't' ? 'h' : arr[i];
return new String(result);
}
}
輸出:
Actual String :- httthhhtth
httth
hhtth
tthht
uj5u.com熱心網友回復:
要進行替換,您需要迭代字符并使用if它來測驗它是什么字符
String base = "httthhhtth";
System.out.println(base);
char[] c = base.toCharArray();
for (int i = c.length / 2; i < c.length; i) {
if (c[i] == 'h') {
c[i] = 't';
} else if (c[i] == 't') {
c[i] = 'h';
}
}
String swappedString = new String(c);
System.out.println(swappedString);
httthhhtth
httthtthht
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514907.html
標籤:爪哇数组细绳
上一篇:如何在HTML中使用onclick獲取按下的按鈕的值。我有6個具有相同類名但值不同的按鈕
下一篇:如何從陣列創建命名物件?
