- 获取字符串长度:
NSString *str = @"Hello World";
NSUInteger length = str.length;
NSLog(@"字符串长度: %lu", (unsigned long)length);
- 字符串拼接:
NSString *str1 = @"Hello";
NSString *str2 = @" World";
NSString *result = [str1 stringByAppendingString:str2];
NSLog(@"拼接后的字符串: %@", result);
- 字符串比较:
NSString *strA = @"apple";
NSString *strB = @"banana";
NSComparisonResult result = [strA compare:strB];
if (result == NSOrderedAscending) {
NSLog(@"%@在%@之前", strA, strB);
} else if (result == NSOrderedDescending) {
NSLog(@"%@在%@之后", strA, strB);
} else {
NSLog(@"%@和%@相等", strA, strB);
}
- 字符串查找:
NSString *str = @"Hello World, Hello iOS";
NSRange range = [str rangeOfString:@"Hello"];
if (range.location != NSNotFound) {
NSLog(@"找到字符串,起始位置: %lu,长度: %lu", (unsigned long)range.location, (unsigned long)range.length);
} else {
NSLog(@"未找到字符串");
}
- 字符串替换:
NSString *str = @"Hello World";
NSString *newStr = [str stringByReplacingOccurrencesOfString:@"World" withString:@"iOS"];
NSLog(@"替换后的字符串: %@", newStr);
- 字符串转大写:
NSString *str = @"hello world";
NSString *upperStr = [str uppercaseString];
NSLog(@"大写后的字符串: %@", upperStr);
- 字符串转小写:
NSString *str = @"HELLO WORLD";
NSString *lowerStr = [str lowercaseString];
NSLog(@"小写后的字符串: %@", lowerStr);