Article Directory
foreword
I brushed the questions on Niuke.com today, and it was very interesting to encounter a question. It is still a bit difficult for me at this stage, so I will share it with you now.
1. Topic
将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I
Input description:
Each test input contains 1 test case: I like beijing. The length of the input case does not exceed 100
Output description:
Output the reversed strings in sequence, separated by spaces
2. Algorithm Explanation
the whole idea:
First, lead to each word, such as I like beijing. After the inversion, it will be I ekil .gnijieb , and then invert the entire character array, which happens to be beijing. like I
#include <stdio.h>
#include <string.h>
void reverse(char* left, char* right)
{
while (left < right)
{
char tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
int main()
{
char str[101] = {
0 };
gets(str); //输入字符数组
char* p = str;//将字符数组首元素地址放到指针变量p中
while (*p) //判断当*p指向'\0'时循环结束,单词倒置完成
{
char* start = p;
char* end = p;
//当末指针指向空格或者正好是最后一个单词指向'\0',循环结束
while (*end != ' ' && *end != '\0')
//让end指针指向单词最后一个字母
{
end++;
}
reverse(start, end-1); //字符串倒置函数,比较简单
p = end + 1;//令指针p指向下一个单词,循环进入下一个单词的倒置
}
int len = strlen(str); //求出整个字符串的长度
reverse(str, str + len - 1);//整个字符串进行倒置
puts(str); //输出倒置后的字符串
return 0;
}