zoukankan      html  css  js  c++  java
  • 翻转句子中单词的顺序

    题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。

    例如输入“I am a student.”,则输出“student. a am I”。


     

    #include <iostream>
    using namespace std;
    void reverse_part(char*,int pBegin,int pEnd);
    void reverse(char *str)
    {
    	//n为字符串长度
    	int n=strlen(str)-1;
    	reverse_part(str,0,n);
    	int pBegin=0,pEnd=0;
    
    	while(str[pEnd+1]){
    		if(str[pEnd]!=' ' && str[pEnd]!='\0')
    			++pEnd;
    		//找到空格
    		else{
    			reverse_part(str,pBegin,pEnd-1);
    			//如果下一个还是空格
    		    while(str[pEnd+1]!='\0' && str[pEnd+1]==' ')
    				++pEnd;
    			pBegin=++pEnd;
    		}
    	}
    	cout<<str<<endl;
    }
    
    void reverse_part(char *str,int pBegin,int pEnd)
    {
    	char temp;
    	for(int i=pBegin;i<=(pEnd-pBegin)/2;++i){
    		temp=str[i];
    		str[i]=str[pEnd-i];
    		str[pEnd-i]=temp;
    	}
    }
    
    void main()
    {
    	char str[]="I am a student.";
    	reverse(str);
    	system("pause");
    }


  • 相关阅读:
    poj1837 Balance

    字符流
    字节流
    File类
    this和static
    异常
    接口
    抽象类
    多态
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/2985690.html
Copyright © 2011-2022 走看看