zl程序教程

您现在的位置是:首页 >  其它

当前栏目

(字符串)句子翻转

字符串 翻转 句子
2023-09-14 09:00:36 时间

题目:

翻转句子中全部的单词,单词内容不变,例如

I’m a student. ---->student. a I’am

思路:

与前面数组循环移动或翻转是一样的思路。

1、每个单词单独翻转,如m’I a .tneduts

2、翻转整个句子,如student. a I’m

由于这里是全部翻转,所以先单独翻转,后整个翻转和先整个翻转,在单独翻转的效果是一样的。

代码:

#include <iostream>

using namespace std;

void reverse(string &str,int start,int end){
    char tmp;
    int i=start;
    int j=end;
    while(i<j){
        tmp=str[i];
        str[i]=str[j];
        str[j]=tmp;
        i++;
        j--;
    }
}

void reverse_sentence(string &str){
    int len=str.length();
    int start=0;
    int index=0;
    while(index<len){
        while(str[index]!=' ' && index<len)
            index++;
        reverse(str,start,index-1);
        while(str[index]==' ' && index<len)
            index++;
        start=index;
    }
    reverse(str,0,len-1);
}

int main()
{
    string str="I'm a student!";
//    cout<<str.length()<<endl; //15
//    cout<<sizeof(str)<<endl;  //4
    reverse_sentence(str);
    cout<<str<<endl;
    return 0;
}

 

运行结果:

image