新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

NSString的几个方法(rangeOfString,hasPrefix,hasSuffix,改变大小写),string(n,“str”)

发布时间:2023-09-13 08:07:17

NSString的几个方法(rangeOfString,hasPrefix,hasSuffix,改变大小写)

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 *lowercase = [str lowercaseString];
NSString *uppercase = [str uppercaseString];
NSString *capitalized = [str capitalizedString];
NSLog(@"Lowercase: %@", lowercase);
NSLog(@"Uppercase: %@", uppercase);
NSLog(@"Capitalized: %@", capitalized);
```
这些方法可以用于查找子字符串、判断前缀和后缀、和改变字符串的大小写。