题解 | #倒置字符串#
倒置字符串
https://www.nowcoder.com/practice/ee5de2e7c45a46a090c1ced2fdc62355
#include <stdio.h>
#include <assert.h>
#include <string.h>
void reverse(char* left,char* right)
{
assert(left);
assert(right);
while(left<right)
{
char tmp = * left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
int main() {
char arr[101]={0};
//输入
gets(arr);//I like beijing.
//逆置
int len = strlen(arr);
//逆序整个字符串
reverse(arr,arr+len-1);
//逆序每个单词
char* start = arr;
while(*start)
{
char * end = start;
while(*end != ' ' && *end != '\0')
{
end++;
}
reverse(start,end-1);
if(*end != '\0')
end++;
start = end;
}
printf("%s\n",arr);//beijing. like I
return 0;
}
fatkun