当前位置: 代码迷 >> 综合 >> 牛客网—倒置字符串 I like beijing. 变为beijing. like I
  详细解决方案

牛客网—倒置字符串 I like beijing. 变为beijing. like I

热度:6   发布时间:2023-11-29 13:55:26.0

思想:

1.先将空格前的字符串逆置

i like beijing. 变为 i ekil .gnijieb

2.然后在逆置整个数组里字符串的内容i ekil .gnijieb变为beijing. like i

//倒置字符串】将一句话的单词进行倒置,标点不倒置。
//比如 I like beijing. 经过函数后变为:beijing. like I//思想:
//先把每个空格前的字符都逆置了先  将I like beijing.变为I ekil .gnijieb
//再把整个数组的内容都逆置                             beijing. like I
#include<stdio.h>
void reversed(char* arr, int start, int end)
{int left = start;int right = end;while (left < right){int tmp = 0;tmp = arr[left];arr[left] = arr[right];arr[right] = tmp;left++;right--;}
}
int main()
{char arr[100] = { 0 };gets(arr);                     //gets(arr)与sizeof("%d",&arr)的区别是可以将空格输入进去int len = strlen(arr);int start = 0;int end = start;while (arr[end] != '\0'){while ((arr[end] != ' ') && (arr[end] != '\0')){end++;                                //计算空格前的字符个数}//先把每个空格前的字符都逆置了先reversed(arr, start, end - 1);            //如果不减1的话end指向的就是空格if (arr[end] == '\0'){start = end;}else{start = end + 1;                      //start变成空格后第一个元素}end = start;}//把整个数组的内容都逆置                      reversed(arr, 0,len-1);                      printf("%s", arr);return 0;
}