有一个字符数组的内容为:”student a am i”,请你将数组的内容改为”i am a student”.
首先把字符串整体翻转,得到的字符串为“i ma a tneduts”,然后对每个单词进行翻转。定义一个翻转字符串的函数str_reverse,这个函数有两个参数,翻转的起始地址char* begin,翻转的结束地址char* end.此函数并不需要参数数组,因为begin和end一定是数组的地址。定义一个reverse函数,该函数有一个参数,要翻转的字符串。要对字符转整体翻转需要,定义两个指针,begin指向数组的首地址,end也指向数组的首地址,如果end指向的内容不是字符串结束标志‘\0’,把end加1.把begin和end传给函数str_reverse就可以整体翻转。
要对每个单词进行翻转,还需在定义一个指针wordend用来表示单词的结束。把begin,end指向数组首地址,如果end指向的内容不是空格或者’\0’,把end加1.如果end指向的内容是空格,把wordend指向end-1,这样一个单词就找到了。把begin,wordend传给函数str_revese就对单词进行了翻转。找下一个单词时,只需把begin指向end+1,如果end+1是空格,把begin加1。
当end指向‘\0’时,end还需要加1,因为如果结束循环,最后一个单词将无法翻转。结束循环的条件应该为*(end-1)==’\0’.
代码如下
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
void swap(char* a, char* b)
//交换一个字符
{
assert(a != NULL && b != NULL);
char tmp = *a;
*a = *b;
*b = tmp;
}
void str_reverse(char *begin, char *end)
//就地反转指定区间[begin, end]的字符串
{
assert(begin != NULL && end != NULL);
while (begin < end) {
swap(begin, end);
begin++;
end--;
}
}
void reverse(char *s)
{
assert(s != NULL);
char *begin = s;
char *end = begin;
for (; *end != '\0'; end++)
;
--end;
//now end point to the last char;
//---reverse strline---
str_reverse(begin, end);
//now strline reversed!
begin = s;
end = begin;
char* wordend = NULL;
do {
if (*end == ' ' || *end == '\0')
{
wordend = end - 1;
//---reverse current word
str_reverse(begin, wordend);
//next time begin pointer should point to next word
begin = end;
while (*begin == ' ')
begin++;
//now begin pointer point to a new word
}
end++;
} while (*(end - 1) != '\0');
}
int main()
{
char ch[] = "student a am i";
reverse(ch);
printf("%s", ch);
system("pause");
return 0;
}