来看一道经典的面试题,题目要求如下:
给定一个字符串“I love china”,编写程序完成以单词为单位的逆序,如“china love i”,并要求不允许使用第三方变量保存数据,但可以使用辅助指针变量等。
这道题主要考察字符串的遍历查找以及分类处理,首先确定算法,我们可以这样处理字符串:
- 将字符串整体导致:“anihc evol i”
- 然后再次遍历字符串,将每个单词倒置:“china love i”
确定完算法后就可以用程序进行操作了,以下是程序的实现过程:
#include <stdio.h>
#define N 32
int swap(char *head ,char *tail);
int main(int argc, const char *argv[])
{
char buff[N] = "I love china";
char *head = buff, *tail = buff;
puts(buff);
//先将尾指针定位到字符串尾部。
while('\0' != *tail)
tail ++;
//调用swap函数将整个字符串倒置。
swap(buff, tail - 1);
//主函数开始扫描遍历整个倒置后的字符串。
while('\0' != *head)
{
//查找单词头
while(32 == *head)
head++;
//找到头后将尾定位到头,开始找单词尾。
tail = head;
while(32 != *tail && '\0' != *tail)
tail++;
//前两 步找到头之后将单词倒置(因为循环结束后tail指向'\0',所以tail-1)。
swap(head,tail - 1);
//单词倒置后将头指向尾,为下次找单词做准备。
head = tail;
}
puts(buff);
return 0;
}
//swap函数,完成指定字符串倒置。
int swap(char *head, char *tail)
{
while(head < tail)
{
//异或法进行交换数据
*head ^= *tail;
*tail ^= *head;
*head ++ ^= *tail--;
}
}