加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

单词倒置

发布时间:2020-12-13 22:43:47 所属栏目:百科 来源:网络整理
导读:如"i am a student" 倒置为 "student a am i" 思路: 1)倒置整个字符串 2)倒置每个单词 #include iostream#include string.husing namespace std;void Reverse_word(char *p,char *q){ if (p==q) { return; } while (pq) { char tmp=*p; *p=*q; *q=tmp; q-

如"i am a student" 倒置为 "student a am i"

思路:

1)倒置整个字符串

2)倒置每个单词

#include <iostream>
#include <string.h>
using namespace std;


void Reverse_word(char *p,char *q){
    
    if (p==q) {
        return;
    }
    
    while (p<q) {
        char tmp=*p;
        *p=*q;
        *q=tmp;
        
        q--;
        p++;
    }
    
}

void Reverse_sentance(char pSentance[]){
    
    if (pSentance==NULL) {
        return;
    }
    
    Reverse_word(pSentance,pSentance+strlen(pSentance)-1);
    
    char *pBegin=pSentance;
    char *pEnd=pSentance;
    
    while (*pEnd!='') {
        if (*pEnd!=' ') {
            pEnd++;
        }else{
            Reverse_word(pBegin,pEnd-1);
            pBegin=++pEnd;
        }
    }
    
    Reverse_word(pBegin,pEnd-1);//逆转最后一个词
}


int main(){
    
    char p[]="i am a student";
    printf("%sn",p);
    Reverse_sentance(p);
    printf("%sn",p);
    
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读