文字列.replace() / trim()
| 対応: | Kotlin 1.0(2016) |
|---|
文字列内の特定の部分を置換したり、文字列の前後から空白や指定した文字を取り除くための関数です。
構文
// 文字列の一部を置換する 文字列.replace(oldValue: String, newValue: String, ignoreCase: Boolean = false) // 文字列の前後から空白を取り除く 文字列.trim() 文字列.trimStart() // 先頭のみ 文字列.trimEnd() // 末尾のみ
メソッド一覧
| メソッド | 概要 |
|---|---|
| replace(oldValue, newValue, ignoreCase) | 一致するすべての文字列を置換します。大文字小文字を区別するかどうかを指定できます。 |
| replace(regex: Regex, replacement: String) | 正規表現にマッチした部分をすべて置換します。 |
| replaceFirst(oldValue, newValue) | 最初に一致した箇所だけを置換します。 |
| trim() | 文字列の前後にある空白文字(半角スペース・タブ・改行など)をすべて除去します。 |
| trimStart() | 文字列の先頭にある空白文字のみを除去します。 |
| trimEnd() | 文字列の末尾にある空白文字のみを除去します。 |
| trim(predicate) | ラムダで指定した条件に一致する文字を前後から除去します。 |
サンプルコード
sample_string_replace_trim.kt
fun main() {
// 特定の文字列を置換する
val text = "Hello, World! Hello, Kotlin!"
val replaced = text.replace("Hello", "Hi")
println(replaced) // Hi, World! Hi, Kotlin!
// 大文字小文字を無視して置換する
val noCase = text.replace("hello", "Hey", ignoreCase = true)
println(noCase) // Hey, World! Hey, Kotlin!
// 最初の一致箇所だけ置換する
val firstOnly = text.replaceFirst("Hello", "Greetings")
println(firstOnly) // Greetings, World! Hello, Kotlin!
// 正規表現で置換する
val digits = "abc123def456"
val noDigits = digits.replace(Regex("[0-9]+"), "#")
println(noDigits) // abc#def#
// 前後の空白を取り除く
val padded = " Kotlin "
println(padded.trim()) // "Kotlin"
println(padded.trimStart()) // "Kotlin "
println(padded.trimEnd()) // " Kotlin"
// 条件に一致する文字を除去する
val slashed = "///path/to/file///"
println(slashed.trim('/')) // path/to/file
}
string_replace_trim.kt
kotlinc string_replace_trim.kt -include-runtime -d string_replace_trim.jar java -jar string_replace_trim.jar Hi, World! Hi, Kotlin! Hey, World! Hey, Kotlin! Greetings, World! Hello, Kotlin! abc#def# Kotlin Kotlin Kotlin path/to/file
よくあるミス
NG例1: 『replace()』の戻り値を変数に受け取らずに捨てる。Kotlin の文字列はイミュータブルなので元の文字列は変更されません。
val message = "item_a を item_b に替える"
message.replace("item_a", "item_c") // 戻り値を使っていない
println(message) // item_a を item_b に替える(元の文字列のまま)
修正後は次の通りです。
// 戻り値を変数に受け取る
val message = "item_a を item_b に替える"
val updated = message.replace("item_a", "item_c")
println(updated) // item_c を item_b に替える
NG例2: 『trim()』に文字列を渡そうとするとコンパイルエラーになる。『trim()』の引数は Char またはラムダです。
val path = "///data/config///"
println(path.trim("///")) // コンパイルエラー: None of the following candidates is applicable
修正後は次の通りです。
// Char を渡すか、ラムダで条件を指定する
val path = "///data/config///"
println(path.trim('/')) // data/config
NG例3: 最初の1件だけ置換したいときに『replace()』を使うと全件置換されてしまう。
val dialog = "item_x item_x item_x!"
val result = dialog.replace("item_x", "item_y")
println(result) // item_y item_y item_y!(全部置換されてしまう)
修正後は次の通りです。
// 最初だけ置換したい場合は replaceFirst を使う
val dialog = "item_x item_x item_x!"
val result = dialog.replaceFirst("item_x", "item_y")
println(result) // item_y item_x item_x!
概要
『replace()』は文字列内で一致するすべての部分を新しい文字列に置換します。デフォルトでは大文字小文字を区別しますが、『ignoreCase = true』を指定すると区別しなくなります。正規表現を使う場合は『Regex』オブジェクトを第1引数に渡してください。
『trim()』はデフォルトで半角スペース・タブ・改行などの空白文字を取り除きます。ラムダを引数に渡すと除去する文字の条件を自由に指定できます。これらのメソッドはすべて新しい文字列を返し、元の文字列は変更されません。Kotlinの文字列はイミュータブルです。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。