我是目标c和iOS的新手。 我有一个像这样的字符串
NSString *string1 = @"My name is john";
我只想反转约翰'到了' nhoj'。 请帮我!!!。 谢谢
答案 0 :(得分:1)
你走了。 可能会在以下片段后帮助您。
NSString *string1 = @"My name is john";
NSArray *arr = [string1 componentsSeparatedByString:@" "];
NSString *temp_sre = [arr objectAtIndex:arr.count - 1];
int len = [temp_sre length];
NSMutableString *reverseName = [[NSMutableString alloc] initWithCapacity:len];
for(int i=len-1;i>=0;i--)
{
[reverseName appendString:[NSString stringWithFormat:@"%c",[temp_sre characterAtIndex:i]]];
}
NSLog(@"reverseName = %@",reverseName);
NSMutableArray *final_array = [[NSMutableArray alloc] init];
final_array = arr.mutableCopy;
[final_array removeLastObject];
[final_array insertObject:reverseName atIndex:final_array.count];
NSString *final_string = [final_array componentsJoinedByString:@" "];
NSLog(@"FInal String = %@",final_string);
答案 1 :(得分:1)
试试这个,它会产生你想要的输出。
NSString *strName = @"My name is john" ;
NSArray *arrStringPart = [strName componentsSeparatedByString:@" "];
NSString *strToReverse = [arrStringPart objectAtIndex:arrStringPart.count - 1];
int len = (int)[strToReverse length];
NSMutableString *mutStrReverce = [[NSMutableString alloc] initWithCapacity:strName.length];
for(int i=0;i<arrStringPart.count-1;i++)
{
[mutStrReverce appendString:[NSString stringWithFormat:@"%@ ",[arrStringPart objectAtIndex:i]]];
}
for(int i=len-1;i>=0;i--)
{
[mutStrReverce appendString:[NSString stringWithFormat:@"%c",[strToReverse characterAtIndex:i]]];
}
NSLog(@"%@",mutStrReverce);