2 回答
TA貢獻1829條經(jīng)驗 獲得超7個贊
您可以按如下方式進行操作:
public class Test {
public static void main(String args[]) {
String str = "Hello World!";
String newStr = "";
int startFrom = 2, endBefore = 5;// test startFrom and endBefore indices
for (int i = startFrom; i < endBefore; i++)
newStr += String.valueOf(str.charAt(i));
System.out.println(newStr);
}
}
輸出:
llo
使用StringBuilder有兩個明顯的優(yōu)點:
在將值附加到字符串之前,您不需要將值String.valueOf轉(zhuǎn)換char為value,因為StringBuilder支持直接向其附加值。Stringchar
您可以避免創(chuàng)建大量String對象,因為由于它String是一個不可變的類,因此每次嘗試更改字符串都會創(chuàng)建一個新String對象。你可以在這里查看一個很好的討論。
public class Test {
public static void main(String args[]) {
String str = "Hello World!";
StringBuilder newStr = new StringBuilder();
int startFrom = 2, endBefore = 5;// test startFrom and endBefore indices
for (int i = startFrom; i < endBefore; i++)
newStr.append(str.charAt(i));
System.out.println(newStr);
}
}
TA貢獻1805條經(jīng)驗 獲得超10個贊
我假設(shè)這是一個家庭作業(yè)問題,但如果您想要提示,您可以使用它myString.toCharArray()來提取char[]字符串中每個字符的 a 并myString.charAt(0)獲取索引 0 處的字符。
您還可以從字符數(shù)組構(gòu)造一個新的字符串,new String(myCharArray)因此您可以簡單地
獲取原始字符串并獲取字符數(shù)組(
char[] myChars = myString.toCharArray();例如)將字符數(shù)組復(fù)制到一個新的、更短的數(shù)組中 (
char[] mySubstringChars = ...)將較短的 char 數(shù)組更改回 String (
String mySubstring = new String(mySubstringChars);)
添加回答
舉報
