0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

大きな数値を 3 けたごとにカンマ区切りで出力 Swift編(paizaランク C 相当)

Last updated at Posted at 2025-05-20

概要

Paiza問題集で手こずったところを備忘録として記録します
※他コードの解き方でより良くなるなどありましたら、お申し付けください!

→ご指摘あり、本来数値表記は、位の小さい後ろからカンマを挿入していきますので、こちら回答の改善が必要になります。その内容を反映させたものをまた編集してのっけたいと思います
問題はこちら

解答コード

Swift
import Foundation

// 入力値を受け取る
let inputNumber = readLine()!

// for文で1文字ずつ取り出す
for fetchedCharacter in 0..<inputNumber.count {
// 0文字目はカンマなし、かつ3文字単位でカンマを出力
if fetchedCharacter % 3 == 0 && fetchedCharacter != 0 {
// 改行なしで出力
print(",", terminator: "")
}
// 文字列が今何文字目かを判定するメソッド
let index = inputNumber.index(inputNumber.startIndex, offsetBy: fetchedCharacter)
// 3文字ごとにカンマ区切りで出力
print(inputNumber[index], terminator: "")
}
0
1
8

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?