1难礼、實現(xiàn)一個字符串“how are you”的逆序輸出(編程語言不限)夭问。如給定字符串為“hello world”,輸出結(jié)果應(yīng)當為“world hello”悍缠。
- (void)charReverse
{
NSString * string = @"hello,world";
NSLog(@"%@",string);
NSMutableString * reverString = [NSMutableString stringWithString:string];
for (NSInteger i = 0; i < (string.length + 1)/2; i++) {
[reverString replaceCharactersInRange:NSMakeRange(i, 1) withString:[string substringWithRange:NSMakeRange(string.length - i - 1, 1)]];
[reverString replaceCharactersInRange:NSMakeRange(string.length - i - 1, 1) withString:[string substringWithRange:NSMakeRange(i, 1)]];
}
NSLog(@"reverString:%@",reverString);
//C
char ch[100];
memcpy(ch, [string cStringUsingEncoding:NSUTF8StringEncoding], [string length]);
//設(shè)置兩個指針阔加,一個指向字符串開頭奏候,一個指向字符串末尾
char * begin = ch;
char * end = ch + strlen(ch) - 1;
//遍歷字符數(shù)組,逐步交換兩個指針所指向的內(nèi)容未巫,同時移動指針到對應(yīng)的下個位置窿撬,直至begin>=end
while (begin < end) {
char temp = *begin;
*(begin++) = *end;
*(end--) = temp;
}
NSLog(@"reverseChar[]:%s",ch);
}
[cpp] view plain copy
int spliterFunc(char *p) {
char c[100][100];
int i =0;
int j =0;
while (*p !='\0') {
if (*p ==' ') {
i++;
j = 0;
} else {
c[i][j] = *p;
j++;
}
p++;
}
for (int k = i; k >=0; k--) {
printf("%s", c[k]);
if (k >0) {
printf(" ");
} else {
printf("\n");
}
} return0;
}