编写一个C函数,将”I am from shanghai ”倒置为”shanghai from am I”,及将句子中的单词位置倒置,而不改变单词内部结构.

来源:互联网 发布:淘宝仓库发货总结 编辑:程序博客网 时间:2024/05/22 10:53

主程序:

#include <stdio.h>


#include <string.h>


#define MAX_SIZE 1024
int main()
{
char src[MAX_SIZE];


printf("please input a string:");
gets(src);


reserve_string(src,strlen(src));


reserve_word(src);


printf("the string is :%s\n",src);


    return 0;
}

字符串逆序:



void reserve_string(char *sl,int len)


{
int i;
char temp;


for(i = 0; i < len / 2; i++)
{
temp = *(sl + i);
*(sl + i) = *(sl + len - i - 1);
*(sl + len - i - 1) = temp;
}






}

单词逆序:

void reserve_word(char *src)
{
int word_len = 0;


while(*src != '\0')
{
if(*src == ' ')
{
reserve_string(src - word_len,word_len);
   word_len = 0;


}
else
{
word_len++;


}
src++;
}
reserve_string(src - word_len,word_len);






}

0 0
原创粉丝点击