Swift中国語教程(三)文字列と文字

10570 ワード

文字列Stringは「hello,world」「albatross」のような文字列です.Swiftの文字列はStringキーワードで定義され、Characterで定義される文字の集合でもあります.
 
SwiftのStringとCharacterタイプは、Unicodeと互換性のある文字ソリューションをコードに迅速に提供します.Stringタイプの初期化と使用はいずれも読み取り可能であり、Cのstringsと類似している.同時にStringは+演算子を使用して組み合わせることもでき、文字列を使用するのはSwiftの他の基本タイプを使用するのと同じように簡単です.
 
1、文字列定数
 
Stringによって定義された文字列定数は、コードで使用できます.定義は非常に簡単です.
let someString = “Some string literal value”
文字列定数には、次のような特殊文字を含めることができます.
空白の文字0、反スラッシュ、タブt、改行、戻り文字r、二重引用符および一重引用符’
単一バイトUnicode文字、xnn、nnは2つの16進数です
2バイトのUnicode文字、unnnn、ここでnnnnは4つの16進数です
4バイトのUnicode文字、Unnnnnnnn、ここでnnnnnnnは8つの16進数です
 
次のコードは、この4つの文字列の例を示します.
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\x24" // $, Unicode scalar U+0024
let blackHeart = "\u2665" // ♥, Unicode scalar U+2665
let sparklingHeart = "\U0001F496" // , Unicode scalar U+1F496

 
2、空白列を初期化する
 
1つの空の列を初期化するには2つの形式がありますが、2つの初期化方法の結果は同じで、空の列を表します.
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer syntax
// these two strings are both empty, and are equivalent to each other

 
isEmptyプロパティを使用して、文字列が空であるかどうかを確認できます.
if emptyString.isEmpty {
println("Nothing to see here")
}
// prints "Nothing to see here"

 
3、文字列が長くなる
 
varキーワードで定義された文字列が修正可能な変長文字列であり、letキーワードで定義された文字列が定数文字列である場合、修正できません.
var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"
let constantString = "Highlander"
constantString += " and another Highlander"
// this reports a compile-time error - a constant string cannot be modified 

 
4、文字列はポインタではなく、実際の値です
 
Swiftでは、Stringタイプは実際の値であり、新しいStringを定義し、前のString値をコピーすると、ポインタのように過去を指すのではなく、実際に等しい新しい値が作成されます.
 
同様に、関数がパラメータを渡す場合も、実際の値が渡され、新しい文字列が作成され、後続の操作で元のString文字列は変更されません.
 
 
5、文字
 
Swiftの文字列Stringは文字Characterからなり、各Characterは特定のUnicode文字を表しています.for-inループにより、文字列の各文字を巡回できます.
for character in "Dog!" {
println(character)
}
// D
// o
// g
// !
//

 
個別の文字を1つだけ定義することもできます.
let yenSign: Character = "¥"

 
6、文字数
 
グローバル関数countElementsを使用して、文字列の文字数を計算します.
let unusualMenagerie = "Koala , Snail , Penguin , Dromedary "
println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"

 
7、文字と文字列の組み合わせ
 
StringタイプとCharacterタイプは、+記号加算を使用して新しい文字列に組み合わせることができます.
let string1 = "hello"
let string2 = " there"
let character1: Character = "!"
let character2: Character = "?"
let stringPlusCharacter = string1 + character1 // equals "hello!"
let stringPlusString = string1 + string2 // equals "hello there"
let characterPlusString = character1 + string1 // equals "!hello"
let characterPlusCharacter = character1 + character2 // equals "!?"

 
+=番号を使用してグループ化することもできます.
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
var welcome = "good morning"
welcome += character1
// welcome now equals "good morning!"

 
8、文字列を使用して新しい列を生成する
 
既存の文字列では、次の方法で新しい文字列を生成できます.
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"

 
上記の例では、まずmultiplierという文字列3を用いて、新しい列の一部として、(multiplier)で追加し、同時に上記の例ではタイプ変換Double(multiplier)を用いて、計算結果と文字列自体を要素として新しい文字列に追加した.
 
9、文字列比較Swiftは文字列の値を比較する3つの方法を提供する:文字列が等しく、接頭辞が等しく、接尾辞が等しい
 
文字列が等しい2つの文字列が完全に同じ文字を含む場合、彼らは等しいと判断される.
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
//  ”These two strings are considered equal”

 
プレフィックス(prefix)等しいと接尾辞(hasSuffix)等しいstringクラスの2つのメソッドhasPrefixとhasSuffixを使用して、1つの文字列のプレフィックスまたは接尾辞に別の文字列が含まれているかどうかを確認します.Stringタイプのパラメータとブールクラスの値を返す必要があります.どちらの方法も、元の文字列と接頭辞文字列または接尾辞文字列の間で文字と文字の間を作成します.
 
次の例では、シェークスピアのロミオとジュリエットの前の2幕のシーンを文字列配列で再現します.
let romeoAndJuliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
"Act 1 Scene 3: A room in Capulet's mansion",
"Act 1 Scene 4: A street outside Capulet's mansion",
"Act 1 Scene 5: The Great Hall in Capulet's mansion",
"Act 2 Scene 1: Outside Capulet's mansion",
"Act 2 Scene 2: Capulet's orchard",
"Act 2 Scene 3: Outside Friar Lawrence's cell",
"Act 2 Scene 4: A street in Verona",
"Act 2 Scene 5: Capulet's mansion",
"Act 2 Scene 6: Friar Lawrence's cell"
]

 
hasPrefixメソッドとromeoAndJuliet配列を使用して、第1幕で何シーンを演じるかを計算することができます.
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
++act1SceneCount
}
}
println("There are \(act1SceneCount) scenes in Act 1")
//  ”There are 5 scenes in Act 1”

 
同じように、hasSuffixメソッドを使用して、Capulet公館とFriar Lawrence牢屋で発生したシーンの数を計算します.
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if scene.hasSuffix("Capulet's mansion") {
++mansionCount
} else if scene.hasSuffix("Friar Lawrence's cell") {
++cellCount
}
}
println("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
//    "6 mansion scenes; 2 cell scenes”

 
大文字と小文字の文字列StringタイプのuppercaseStringとlowercaseStringから文字列の大文字と小文字を取得できます.
let normal = "Could you help me, please?"
let shouty = normal.uppercaseString
// shouty is equal to "COULD YOU HELP ME, PLEASE?"
let whispered = normal.lowercaseString
// whispered is equal to "could you help me, please?"

 
10、Unicode Unicodeはテキストを符号化して表す国際標準である.すべての言語のすべての文字の標準的な形態をほとんど表示できます.テキストファイルやWebページのような外部ソースファイルから文字を読み取り、変更することもできます.
 
Unicode用語各Unicode文字は、1つ以上のunicode scalarとして符号化することができる.unicode scalarは、文字または識別子に対応する唯一の21桁(または名前)です.例えば、U+0061は小文字のA(「a」)またはU+1 F 425は私たちに面した黄色いニワトリです.
 
Unicode文字列がテキストまたは他の格納に書き込まれると、unicode scalarはUnicode定義のフォーマットに基づいて符号化されます.各フォーマット符号化文字は、code unitsと呼ばれる小さなコードブロックである.彼はUTF-8フォーマット(各文字列は8ビットのcode unitsからなる)を含む.およびUTF-16フォーマット(各文字列は16ビットのcode unitsからなる)
 
Unicode文字列Swiftは、様々な方法でUnicode文字列を取得することをサポートする.for-in文を使用して文字列を巡回し、各文字のUnicode符号化値を得ることができます.このプロセスはすでに文字で(Working with Characters)について説明した.あるいは、次の3つの説明のうち適当な1つを用いて1つの文字列の値UTF-8文字符号化ユニット集合を得るStringタイプのutf-8属性UTF-16文字符号化ユニット集合を用いてStringタイプのutf-16属性21ビットUnicodeスカラー集合を用いてStringタイプのunicodeScale属性を用いた次の各例を示す異なる符号化表示はD,o,g,!
(DOG FACE、またはUnicodeスカラーU+1 F 436)文字からなる文字列
 
UTF-8 Stringタイプのutf 8プロパティを使用して、UTF-8で符号化された文字列を巡回できます.この属性はUTF 8 Viewタイプであり、UTF 8 Viewは8ビット符号なし整形(UIT 8)の集合であり、集合の各バイトはUTF-8符号化である.
for codeUnit in dogString.utf8 {
print("\(codeUnit) ")
}
print("
") // 68 111 103 33 240 159 144 182

 
上記の例では、最初の4つの10進数codeunit値(68111103,33)が文字列D,o,g,!として表示され、それらのASCII符号化と同様である.後の4つのcodeunitの値(240159144182)はDOG FACE文字の4バイトUTF-8符号化である.
 
UTF-16 Stringタイプのutf 16プロパティを使用して、UTF-16で符号化された文字列を巡回できます.この属性はUTF 16 Viewタイプであり、UTF 16 Viewは16ビット符号なし整形(UIT 16)の集合であり、集合の各バイトはUTF-16符号化である.
for codeUnit in dogString.utf16 {
print("\(codeUnit) ")
}
print("
") // 68 111 103 33 55357 56374

 
同様に、最初の4つの10進数codeunit値(68111103,33)は、文字列D,o,g,および!として表示され、彼らのUTF-16のcodeunitと彼らのUTF-8の符号化値は同じである.
5番目と6番目のcodeunit値(55357および56374)は、DOG FACE文字のUTF-16のプロキシペア符号化である.これらの値は、U+D 83 D(10進55357)の上位プロキシ(lead surrogate)と、U+DC 36(10進56374)の下位プロキシ(trail surrogate)からなる.
 
UnicodeスカラーStringタイプのunicodeScaleプロパティを使用して、Unicodeスカラーで符号化された文字列を巡回できます.この属性はUnicodeScalarsViewタイプであり、UnicodeScalarsViewはUnicodeScalarタイプの集合である.各Unicodeスカラーは任意の21ビットのUnicodeコードビットであり、上位エージェントも下位エージェントもない.
 
各UnicodeScalarはvalue属性を使用して、スカラーの21ビット値を返します.各ビットは32ビットの符号なし整形(UIT 32)の値です.
for scalar in dogString.unicodeScalars {
print("\(scalar.value) ")
}
print("
") // 68 111 103 33 128054

 
value属性は、最初の4つのUnicodeScalar値(68111103,33)で、文字D,o,g,および!が符号化されていることを改めて示している.5番目で最後のUnicodeScalarはDOG FACE文字であり、十進法は1280054であり、UnicodeスカラーのU+1 F 436に相当する16進数の1 F 436に等しい.
各UnicodeScalarは、value属性の読み取りの代わりに新しい文字列として構築することができ、文字列の挿入と同様である.
for scalar in dogString.unicodeScalars { println("\(scalar) ") } 
// D 
// o 
// g 
// ! 
//

 
李起攀(微博)、若晨(微博)、YAO、ちまき、山有木兮木有枝、ちっぽけ-BEssie、墨离、CXH、Tiger大顾(微博)
本文は翻訳グループのメンバーがオリジナルで発表して、个人の転载は出典と原始のリンクを明记して、商业の転载は私达に连络してください~私达の仕事に対する支持に感谢します~
 
回転元:http://letsswift.com/2014/06/strings-and-characters/