今天我重点写一下OC中的NSString和Swift中的String不同,毕竟项目中对字符串的一些运用是不可缺少的!
一、初始化
OC中:
NSString *str = @"OC字符串";
Swift中:
let str:String = "Swift字符串";
二、字符串的比较
OC中:
NSString *str1 = @"Hello";
NSString *str2 = @"World";
//比较两个字符内容是否相等
if ([str1 isEqualToString:str2])
{
NSLog(@"str1和str2是相等的");
}else
{
NSLog(@"str1和str2是不相等的");
}
Swift中:
let str1:String = "Hello";
let str2:String = "World";
if str1 == str2
{
print("str1和str2是相等的");
}else{
print("str1和str2是不相等的");
}
三、字符长度的获取
OC中:
NSString *str1 = @"Hello";
NSInteger length = [str1 length];
NSLog(@"length==%ld",length);
Swift中:
let str1:String = "Hello";
print(str1.count);
四、大小写变化
OC中:
NSString *str = @"c";
NSLog(@"转为大写:%@",str.uppercaseString);
NSLog(@"转为小写:%@",str.lowercaseString);
Swift中:
let str1:String = "c";
//转为大写
print(str1.uppercased());
//转为小写
print(str1.lowercased());
五、字符串转数值
OC中:
NSString *str = @"123";
NSInteger strInt = [str integerValue];
Swift中:
1.将String转为NSString
let str1:String = "123";
(str1 as NSString).intValue
let str = "111";
Int(str)!;
六、遍历字符串获取字符
OC中:
NSString *str = @"hello,world";
for (int i = 0; i < str.length; i++) {
NSLog(@"%c",[str characterAtIndex:i]);
}
Swift中:
let str = "hello,world";
for ch in str {
print(ch);
}
如果有哪些不足之处,欢迎指出!谢谢!!!
网友评论