MST

星途 面试题库

面试题:Objective-C中NSString常用的字符串操作方法有哪些及示例

请列举至少5个NSString类常用的字符串操作方法,并给出简单的代码示例,例如获取字符串长度、字符串拼接、字符串比较等操作。
39.2万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 获取字符串长度
NSString *str = @"Hello World";
NSUInteger length = str.length;
NSLog(@"字符串长度: %lu", (unsigned long)length);
  1. 字符串拼接
NSString *str1 = @"Hello";
NSString *str2 = @" World";
NSString *result = [str1 stringByAppendingString:str2];
NSLog(@"拼接后的字符串: %@", result);
  1. 字符串比较
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);
}
  1. 字符串查找
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(@"未找到字符串");
}
  1. 字符串替换
NSString *str = @"Hello World";
NSString *newStr = [str stringByReplacingOccurrencesOfString:@"World" withString:@"iOS"];
NSLog(@"替换后的字符串: %@", newStr);
  1. 字符串转大写
NSString *str = @"hello world";
NSString *upperStr = [str uppercaseString];
NSLog(@"大写后的字符串: %@", upperStr);
  1. 字符串转小写
NSString *str = @"HELLO WORLD";
NSString *lowerStr = [str lowercaseString];
NSLog(@"小写后的字符串: %@", lowerStr);