LoginSignup
1
2

More than 1 year has passed since last update.

文字列からスペースと改行を削除

Posted at

環境

  • Swift ver 5.5.1

コード

文字列の前後から

利用しているメソッド

スペースを取り除く

let text = " 前後にスペース "
let trimmedText = text.trimmingCharacters(in: .whitespaces)
print(trimmedText, terminator: "") 
// 出力:"前後にスペース"

改行を取り除く

let text = "\n前後に改行\n"
let trimmedText = text.trimmingCharacters(in: .newlines)
print(trimmedText, terminator: "")
// 出力:"前後に改行"

スペースと改行を取り除く

let text = " \n \n前後にスペースと改行 \n "
let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)
print(trimmedText, terminator: "") 
// 出力:"前後にスペースと改行"

文字列の全体から

利用しているプロパティ

  • Apple Developer Documentation - Character / isWhitespace
  • Apple Developer Documentation - Character / isNewline

スペースを取り除く

let text = " 全 体 に  ス  ペ ー  ス "
let trimmedText = text.filter { !$0.isWhitespace }
print(trimmedText, terminator: "")
// 出力:"全体にスペース"

改行を取り除く

let text = "\n\n\n\n\n\n\n\n\n\n"
let trimmedText = text.filter { !$0.isNewline }
print(trimmedText, terminator: "")
// 出力:"全体に改行"

スペースと改行を取り除く

let text = " \n \n全 体 に\n  ス \n ペ ー ス と 改行 \n"
let trimmedText = text.filter { !($0.isWhitespace || $0.isNewline) }
print(trimmedText, terminator: "")
// 出力:"全体にスペースと改行"

利用シーン

コピペなどで入力されたメールアドレスに余分なスペースが含まれていたり、
不適切な文字を検出する際にスペースや改行が文字間に含まれている場合に利用してみてください:rocket:

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