1、实现一个字符串“how are you”的逆序输出(编程语言不限)。如给定字符串为“hello world”,输出结果应当为“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]);
//设置两个指针,一个指向字符串开头,一个指向字符串末尾
char * begin = ch;
char * end = ch + strlen(ch) - 1;
//遍历字符数组,逐步交换两个指针所指向的内容,同时移动指针到对应的下个位置,直至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;
}
网友评论