在Objective-C,我们使用NSString类而非char *来操作字符串,其表示方法也与C语言或C++不同。
(1)创建字符串
- NSString *hellostr = @"Hello World";// Hello World
- NSString *emptystr = [NSString string];// 空字符串
- NSString *twinsstr = [NSString stringWithString:hellostr];// 用hellostr创建字符串twinsstr
- NSString *clstring = [NSString stringWithCstring:"This is a C-String" encoding:NSUTF9StringEncoding];// 用C语言字符串"This is a C-String"创建字符串clstring
- NSString *applestr = [NSString stringWithFormat:@"%@,Hello Apple",hellostr];// 用hellostr字符串来创建格式化的字符串applestr
复制代码
(2)我们可以使用%@占位符来表示一个字符串
- NSString *name = @"Jim";
- NSString *introduce = [NSString stringWithFormat:@"My name is %@",name];
复制代码
(3)拼接字符串的方法stringByAppendingString
- NSString *welcome = @"Welcome";
- NSString *beijing = [welcome stringByAppendingString:@" to Beijing!"];
复制代码
(4)比较字符串的方法isEqualToString
- NSString *str1 = @"Programming in Objective-C";
- NSString *str2 = @"Programming in Swift";
- if([str1 isEqualToString:str2])
- {
- NSSLog(@"Equal");
- }
- else
- {
- NSSLog(@"Not equal");
- }
复制代码
(5)字符串大小写转换的方法uppercaseString和lowercaseString
- NSString *str = @"programming in objective-c";
- NSString *newStr = [str uppercaseString];
- newStr = [str lowercaseString];
复制代码
(6)从开头截取字符串到指定位置的方法substringToIndex(注意:第一个字符的位置为0)
- NSString *str = @"Programming in Objective-C";
- NSString *newStr = [str substringToIndex:5];
复制代码
(7)从指定位置截取字符串到末尾到的方法substringFromIndex
- NSString *str = @"Programming in Objective-C";
- NSString *newStr = [str substringFromIndex:5];
复制代码 |