どうも、ちょげ(@chogetarou)です。
for文で文字列(string)を反転して逆順にする方法を紹介します。
方法

for文で文字列(string)を反転して逆順にするには、charAt()を使います。
まず、変数を用意します。
String result = "";
for文で文字数分ループします。
ループ処理で、「+」の左辺に文字列から呼び出したcharAt()、右辺に変数を指定します。
charAt()の引数には、ループ変数を指定します。
そして、「+」の結果を文字列に代入します。
for (int i = 0; i < text.length(); i++) {
result = text.charAt(i) + result;
}
上記のforループは、変数に文字列を反転して逆順にした結果を格納します。
使用例
public class Main {
public static void main(String[] args) throws Exception {
String text = "012345";
String result = "";
for (int i = 0; i < text.length(); i++) {
result = text.charAt(i) + result;
}
System.out.println(text);
System.out.println(result);
}
}
出力:
012345
543210
コメント