标签:
var str = "Hello, playground" //声明一个字符串
var emptyStr = ""; //声明一个空的字符串
var emptyStr1 = String(); //相等于上面的那个
str.isEmpty; //判断str是不是为空false
emptyStr.isEmpty; //true
var str1 = "hello";
var str2 = "world";
var str = str1 + str2;
for character in str.characters {
print(character);
}
let c: Character = "a"; //‘a‘是错误的
let cat:[Character] = ["c", "a", "t", "!"]; //声明一个字符数组
let catStr = String(cat); //将字符数组变为字符串
let c: Character = "a";
catStr.append(c);
可以使用”(value)”方式往字符串中插入值,构建一个新的字符串
let someNum: Int = 40;
let message = "我有\(someNum)包茶叶";
let num = message.characters.count //message字符串含有的字符
let greet = "good morning";
/*startIndex代表字符串开始的下标*/
greet[greet.startIndex];
/*endIndex代表字符串结束的下面 predecessor代表前一个*/
greet[greet.endIndex.predecessor()];
/*successor表带继续的也就是下一个*/
greet[greet.startIndex.successor()];
/*字符串不支持直接访问下标,需要使用advance函数转化,如果访问的下标超出字符串就会发出运行时错误*/
let index = advance(greet.startIndex, 7);
greet[index];
greet[7] //语法错误
greet[greet.endIndex]; //错误
greet[greet.endIndex.successor()]; //错误
for index in indices(greet) {
print("\(greet[index])");
}
–
var greet = "hello";
/*使用insert插入字符*/
greet.insert("!", atIndex: greet.startIndex);
/*使用splice插入字符组*/
greet.splice("world".characters, atIndex: greet.endIndex);
/*removeAtIndex移除在某个下标的字符*/
greet.removeAtIndex(greet.startIndex);
/*创建一个范围,然后移除这个范围*/
let range = advance(greet.startIndex, 5)..<greet.endIndex;
greet.removeRange(range);
let str1 = "hello";
let str2 = "hello"
str1 == str2; //比较两个字符串是否相等
let strs = ["hello", "morning", "happy"];
for str in strs {
//判断字符串开头是否包含he
if(str.hasPrefix("he")) {
print(str);
//判断字符串结尾是否包含ng
}else if str.hasSuffix("ng") {
print(str);
}
}
标签:
原文地址:http://blog.csdn.net/ttf1993/article/details/46593123