1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

問題概要

文字列Sのa番目とb番目を入れ替えて出力する。

解法と実装

for文で文字列Sの文字を順番に見て、aまたはb番目の時は入れ替えて出力します。
それ以外の時はi番目の文字を出力します。

S = input() # 文字列を受け取る
a, b = map(int, input().split()) #数字を受け取る
a -= 1 # インデックスは0始まりなので、1を引いて合わせる
b -= 1
for i, s in enumerate(S): # iはインデックス、sはSのi番目の文字が入る
  if i == a: # A番目の時
    print(S[b], end="") # end=""で改行を防ぐ
  elif i == b:
    print(S[a], end="")
  else:
    print(s, end="") # a番目でもb番目でもない時はi番目の文字、すなわちsを出力する

備考(よくある間違い)

replaceで文字を入れ替えることができますが、今回は同じ文字が文字列に複数存在することがあるので、使うことができません。

S = input()
a, b = map(int, input().split())
a -= 1
b -= 1
char_a = S[a] # a番目の文字をchar_aとおく
char_b = S[b]
S = S.replace(char_a, "A") # そのまま入れ替えるとchar_aだった場所とchar_bだった場所が混ざるので、一旦ダミーとして"A"に入れ替える
S = S.replace(char_b, char_a)
S = S.replace("A", char_b)
print(S)

このとき、
入力

aabb
1 3

に対して

bbaa

と出力されてしまい、期待する出力である

baab

は出力されません。

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?