NSString的几个方法包括:
- rangeOfString:用于查找子字符串在原字符串中的位置。返回找到的子字符串的范围,若未找到则返回NSNotFound。示例代码:
NSString *str = @"Hello, World!"; NSRange range = [str rangeOfString:@"World"]; if (range.location != NSNotFound) { NSLog(@"Found at index %lu", range.location); } else { NSLog(@"Not found"); }
- hasPrefix:判断字符串是否以指定的前缀开始。返回BOOL值,若是则返回YES,否则返回NO。示例代码:
NSString *str = @"Hello, World!"; if ([str hasPrefix:@"Hello"]) { NSLog(@"Starts with Hello"); } else { NSLog(@"Does not start with Hello"); }
- hasSuffix:判断字符串是否以指定的后缀结束。返回BOOL值,若是则返回YES,否则返回NO。示例代码:
NSString *str = @"Hello, World!"; if ([str hasSuffix:@"World!"]) { NSLog(@"Ends with World!"); } else { NSLog(@"Does not end with World!"); }
- 改变大小写:NSString提供了多个方法用于改变字符串的大小写,包括lowercaseString、uppercaseString、capitalizedString。示例代码:
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);
这些方法可以用于查找子字符串、判断前缀和后缀、以及改变字符串的大小写。