@fiy-fish
2015-07-04T17:07:28.000000Z
字数 676
阅读 1436
Objective-c
/*
//压缩字符串
//比如输入@"aaabbbcceaa" 输出@"3a3b2c1e2a"
+(NSString*)compString:(NSString*)srcStr;
*/
//我的思路
//1.循环取出字符串中得字母,进行比较,如果相同就计数加一
//注意:
//[ str2 appendFormat:@"%d%c",count,a];必须放到else里面
//如果没有
/*f (i == length-2) {
[ str2 appendFormat:@"%d%c",count,a];
}
*/
//程序不会取到最后两个字符,会卡在count++里面
int main()
{
NSString *str1 = @"aaabbbcceaa";
char a,b;
int count = 1;
NSInteger length = [str1 length];
NSLog(@"length = %ld",length);
NSMutableString *str2 = [NSMutableString string];
for (NSInteger i=0; i<length-1; i++) {
a = [str1 characterAtIndex:i];
b = [str1 characterAtIndex:i+1];
if (a==b) {
count++;
}
else
{
[ str2 appendFormat:@"%d%c",count,a];
count = 1;
}
if (i == length-2) {
[ str2 appendFormat:@"%d%c",count,a];
}
}
NSLog(@"str2---->%@",str2);
}