使用C指针颠倒字符串。
例如: "Welcome to India" 变为"India to Welcome"
Reverse a string using C pointers
Ex: "Welcome to India" to "India to Welcome"
算法及例子如下:
先颠倒整个字符串,然后颠倒单个单词。
Welcome to India
after step 1 => aidnI ot emocleW
after step 2 => India to Welcome
Algorithm is:
1. Reverse the whole string.
2. Reverse the individual words.
For example:
Welcome to India
after step 1 => aidnI ot emocleW
after step 2 => India to Welcome
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
void reverse_string(char* str,char * end)
{
char c;
while (str<end)
{
c = *str;
*str = *end;
*end = c;
str++;
end--;
}
}
void reverse_word()
{
char str[MAX_LEN];
printf("input the string:");
fgets(str,MAX_LEN,stdin);//读入的字符串中最后包含读到的换行符 以及结束符
int len = strlen(str);
char*start = str,*end = str + len - 2;
str[len - 1] = '\0';//将结尾之前的换行符置为结束符
reverse_string(start,end);
start = strtok(str," ");
while (start)
{
end = start+strlen(start)-1;
reverse_string(start,end);
start = strtok(NULL," ");
}
for (int i = 0;i<len-1;i++)
{
printf("%c",str[i]);
}
printf("\n");
}
int main()
{
reverse_word();
return 1;
}