问题描述
- OC中删除字符串中相邻的重复字符
-
//去除字符串内的相邻的重复字符,例如:aabdaaadesff,最后结果abdadesfNSMutableString *string = [NSMutableString stringWithFormat:@"aabbssddffiieeoo"]; NSString *strIndex1 = @""; NSString *strIndex2 = @""; for (NSInteger i = 0; i <= [string length]; i++) { strIndex1 = [string substringWithRange:NSMakeRange(i, 1)]; strIndex2 = [string substringWithRange:NSMakeRange(i + 1, 1)]; if ([strIndex1 isEqualTo:strIndex2]) { [string deleteCharactersInRange:NSMakeRange(i + 1, 1)]; } } NSLog(@"%@", string); }
运行出来有错误 希望大神帮看看
解决方案
NSMutableString *string = [NSMutableString stringWithFormat:@"aabbbssddffffiieeoo"];
for (NSInteger i = 0; i < string.length - 1; i++) {
for (NSInteger j = i+1; j < string.length; j++) {
NSString *str1 = [string substringWithRange:NSMakeRange(i, 1)];
NSString *str2 = [string substringWithRange:NSMakeRange(j, 1)];
if ([str1 isEqualToString:str2]) {
[string deleteCharactersInRange:NSMakeRange(j, 1)];
j--;
} else {
break;
}
}
}
解决方案二:
NSString *currentStr=[[NSString alloc]init];
NSString *nextStr=[[NSString alloc]init];
NSString *string = @"abbssddffiieeoi";
NSMutableString *str=[[NSMutableString alloc]init];
int j=1;
for(int i=0;i<string.length;i++){
if(i==string.length-1){
currentStr=[string substringWithRange:NSMakeRange(string.length-1, 1)];
[str appendString:currentStr];
break;
}else{
currentStr=[string substringWithRange:NSMakeRange(i, 1)];
nextStr=[string substringWithRange:NSMakeRange(j, 1)];
if([currentStr isEqualToString:nextStr]){
j++;
}else{
[str appendString:currentStr];
j++;
}
}
}
NSLog(@"%@",str);
解决方案三:
题主的错误是数组越界导致程序奔溃 把原题的等号去掉就 ok 了
reason: '-[__NSCFString substringWithRange:]: Range {8, 1} out of bounds; string length 8
问题很简单 题主要学会自己看错误报告 一般reason后面就是啦 翻译一下就知道了
解决方案四:
删除字符串中重复字符
删除字符串中重复字符
如何删除字符串中重复的字符
解决方案五:
SDFASDFASD
解决方案六:
删除字符串中相邻重复字符
NSMutableString *string = [NSMutableString stringWithFormat:@"ssddjjiirhwiofhjjdkkkd"];
for (int i = 0; i < string.length; i++) {
NSString *str1 = [string substringWithRange:NSMakeRange(i, 1)];
NSString *str2 = [string substringWithRange:NSMakeRange(i - 1, 1)];
if ([str1 isEqualToString:str2]) {
[string deleteCharactersInRange:NSMakeRange(i, 1)];
}
}
NSLog(@"%@", string);
时间: 2024-11-01 14:51:37