1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Swiftでfor文を使って配列の順番を変更する方法。

Last updated at Posted at 2023-08-20

読んで欲しい人

・Swift詳しい方。
・この問題を解く前の私。

注意!

AtCoderのA - Rotateのネタバレあり。

学んだこと

・標準入力から文字列を配列として受け取る。
・配列の要素を追加や削除をしない場合はletでも良い。今回は配列を入れ替えの操作のみ。
・for文でiを利用し、指定した添字(インデックス)を出力する。
・改行しないで出力する方法。

ACしたコード

// Array()で標準入力から文字列を配列として受け取る。
let s = Array(readLine()!)
// print(s)
// 添字を利用したいからiを利用し、添字にアクセスできるようにする。
for i in 0..<3 {
    if i != 0{
// terminator: ""で改行しないようにしている
        print(s[i],terminator: "")        
    }
}
//print()には改行が含まれている。    
print(s[0])    

標準入力
abc
標準出力
bca

いいコードにしてみる

・for文でcountプロパティに変更して3文字以外でも動くコードにする。

let s = Array(readLine()!)
// print(s)
for i in 0..<s.count {
    if i != 0{
        print(s[i],terminator: "")        
    }
}
print(s[0])    

標準入力
abc
標準出力
bca

実験してみた。

・標準入力に,区切りの整数が与えられた場合、空白区切りで出力、最後の文字のみ改行をして出力する方法。
入力例
1,2,3,4,5,6,7,8,9,10
出力例
2 3 4 5 6 7 8 9 10 1

// 標準入力から整数を一行受け取る。
let input = readLine()!
print(input)
// 標準入力で受け取った整数を,区切りで配列にする。
let numSplit = input.split(separator: ",")
print(numSplit)
// 配列の要素数の合計値
print(numSplit.count)
// 0から10(配列の要素数の合計)の間、添字が0以外の時、空白区切りの改行無しで出力する。
for i in 0..<numSplit.count {
    if i != 0{
        print(numSplit[i] + " ",terminator: "")   
    } 
}
// 添字の0番目を出力する。
print(numSplit[0])    

標準入力
1,2,3,4,5,6,7,8,9,10
標準出力
1,2,3,4,5,6,7,8,9,10
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
10
2 3 4 5 6 7 8 9 10 1

参考にした記事

改行を含めない方法 terminator: ""
プロパティ、countの使い方

1
2
2

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?