NSString是Objective-C中常用的字符串处理类,它提供了许多方便的方法来操作字符串。以下是NSString的几个常用方法:
1. rangeOfString:用于查找子字符串在原字符串中的位置。返回找到的子字符串的范围,若未找到则返回NSNotFound。示例代码如下:
```objective-c
NSString *str = @"Hello, World!";
NSRange range = [str rangeOfString:@"World"];
if (range.location != NSNotFound) {
NSLog(@"Found at index %lu", range.location);
} else {
NSLog(@"Not found");
}
```
2. hasPrefix:判断字符串是否以指定的前缀开始。返回BOOL值,若是则返回YES,否则返回NO。示例代码如下:
```objective-c
NSString *str = @"Hello, World!";
if ([str hasPrefix:@"Hello"]) {
NSLog(@"Starts with Hello");
} else {
NSLog(@"Does not start with Hello");
}
```
3. hasSuffix:判断字符串是否以指定的后缀结束。返回BOOL值,若是则返回YES,否则返回NO。示例代码如下:
```objective-c
NSString *str = @"Hello, World!";
if ([str hasSuffix:@"World!"]) {
NSLog(@"Ends with World!");
} else {
NSLog(@"Does not end with World!");
}
```
4. 改变大小写:NSString提供了多个方法用于改变字符串的大小写,包括lowercaseString、uppercaseString、capitalizedString。示例代码如下:
```objective-c
NSString *str = @"Hello, World!";
NSString *lowerCaseStr = [str lowercaseString]; // "hello, world!"
NSString *upperCaseStr = [str uppercaseString]; // "HELLO, WORLD!"
NSString *capitalizedStr = [str capitalizedString]; // "Hello, world!"
```
NSString *str = @"Hello, World!";
NSString *lowercase = [str lowercaseString];
NSString *uppercase = [str uppercaseString];
NSString *capitalized = [str capitalizedString];
NSLog(@"Lowercase: %@", lowercase);
NSLog(@"Uppercase: %@", uppercase);
NSLog(@"Capitalized: %@", capitalized);