1.文字列の反転
(1)再帰
public class Reverse { public static String test(String str){ if(str == null || str.length()<= 1 ) return str; return test(str.substring(1))+ str.charAt(0 ); } public static void main(String [] args){ Reverse reverse = new Reverse(); 文字列string = reverse.test( "abcd" ); System.out.println(string); } }
DCBA
(2)charAtメソッド
public class Reverse { public static String test(String str){ int length = str.length(); 文字列reverse = "" ; for(int i = 0; i <length; i ++ ) reverse = str.charAt(i)+ reverse; 逆戻り; } public static void main(String [] args){ Reverse reverse = new Reverse(); 文字列string = reverse.test( "abcd" ); System.out.println(string); } }
charAtメソッドを使用して、文字列の各文字を個別に取り出し、以前に形成された文字列をスプライスして、逆の文字列を形成します
(3)toCharArray
public class Reverse { public static String test(String str){ char [] array = str.toCharArray(); 文字列reverse = "" ; for(int i = array.length-1; i> = 0; i-- ){ reverse = reverse + array [i]; } 戻ります。 } public static void main(String [] args){ Reverse reverse = new Reverse(); 文字列string = reverse.test( "abcd" ); System.out.println(string); } }
このメソッドは、文字列を文字配列に変換してから、文字配列を(逆順で)トラバースします
(4)StringBuilerまたはStringBufferのreverse()メソッド
public class Reverse { public static String test(String str){ StringBuilder stringBuilder = new StringBuilder(str); stringBuilder.reverse()。toString();を返します。 } public static void main(String [] args){ Reverse reverse = new Reverse(); 文字列string = reverse.test( "abcd" ); System.out.println(string); } }
2.文字列の置換
(1)置換方法:
public class Reverse { public String test(){ String str = "abcde" ; 文字列s = str.replace( 'c'、 '3' ); sを返す; } public static void main(String [] args){ Reverse reverse = new Reverse(); 文字列string = reverse.test(); System.out.println(string); } }
一度に1文字だけを別の文字に置き換えることができます
(2)replaceAllメソッド
public class Reverse { public String test(){ String str = "abcdeab" ; 文字列s = str.replaceAll( "ab"、 "aabb" ); sを返す; } public static void main(String [] args){ Reverse reverse = new Reverse(); 文字列string = reverse.test(); System.out.println(string); } }
aabbcdeaabb
同じ文字列をすべて、置き換える文字列で置き換えます
(3)replaceFirst
public class Reverse { public String test(){ String str = "abcdeab" ; 文字列s = str.replaceFirst( "ab"、 "aabb" ); sを返す; } public static void main(String [] args){ Reverse reverse = new Reverse(); 文字列string = reverse.test(); System.out.println(string); } }
replaceFirstはreplaceAllとは異なり、replaceFirstは最初に出現した文字列のみを置換します