LoginSignup
0
0

More than 3 years have passed since last update.

【JAVA】文字列のn番目を変換する

Last updated at Posted at 2021-05-01

はじめに

String型でn番目の文字を1文字変換する方法としてはSubstringを活用して文字列を分解して再度結合を行うことで実装できるが、いつも第一引数と第二引数で何を入ればよいか混乱するので他の方法を探したところ,StringBuilderのsetChartAt() を活用する方法があったのでまとめる。

サンプルコード

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //変換する元の文字列
        String first_row = "ABCDEFGHIJK";
        //変換するn番目の数値を受け取る。
        int num = 6;
        //setCharAtではchar型を第二引数として与える必要がある。
        char change_char = 'X';
        //String Builderに型変換
        StringBuilder newString = new StringBuilder(first_row);
        //setCharAt(変換する文字のインデックス,変換後のchar)
        newString.setCharAt(num,change_char);
        //ABCDEFXHIJK
        System.out.println(newString);
    }
}

最後に

setCharAtは引数としてあまりなじみのないchar型を使用しないといけないが、Substringを使用するよりも直感的に使いやすいと感じた。
プログラミングコンテストで使うにはStringBuilderを活用することは利点が多そうなので今後は活用していこうと思う。

参考

StringBuilderクラスについて

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0