Java實現字串反轉的幾種方法
阿新 • • 發佈:2019-02-18
2.最常用的方法:
public static String reverse3(String s)
{
char[] array = s.toCharArray(); //將string型別引數轉化為char[]型別引數
String reverse = ""; //注意這是空串,不是null
for (int i = array.length - 1; i >= 0; i--)
reverse += array[i];
return reverse;
}
3.常用方法的變形:
public static String reverse2(String s)
{
int length = s.length();
String reverse = ""; //注意這是空串,不是null
for (int i = 0; i < length; i++)
reverse = s.charAt(i) + reverse;//在字串前面連線, 而非常見的後面
return reverse;
}
4.C語言中常用的方法:
public static String reverse5(String orig)
{
char[] s = orig.toCharArray();
int n = s.length - 1;
int halfLength = n / 2;
for (int i = 0; i <= halfLength; i++) {
char temp = s[i];
s[i] = s[n - i];
s[n - i] = temp;
}
return new String(s); //知道 char陣列和String相互轉化
}
public static String reverse3(String s)
{
char[] array = s.toCharArray(); //將string型別引數轉化為char[]型別引數
String reverse = ""; //注意這是空串,不是null
for (int i = array.length - 1; i >= 0; i--)
reverse += array[i];
return reverse;
}
3.常用方法的變形:
public static String reverse2(String s)
{
int length = s.length();
String reverse = ""; //注意這是空串,不是null
for (int i = 0; i < length; i++)
reverse = s.charAt(i) + reverse;//在字串前面連線, 而非常見的後面
return reverse;
}
4.C語言中常用的方法:
public static String reverse5(String orig)
{
char[] s = orig.toCharArray();
int n = s.length - 1;
int halfLength = n / 2;
for (int i = 0; i <= halfLength; i++) {
char temp = s[i];
s[i] = s[n - i];
s[n - i] = temp;
}
return new String(s); //知道 char陣列和String相互轉化
}