Saturday, July 23, 2011

字串小寫變大寫

// 小寫變大寫.cpp : 定義主控台應用程式的進入點。
//

//一個能把輸入的字串中,所有字第一個字母變大寫,
//和把全部所有字母都變大寫的C++程式


#include "stdafx.h"
#include<iostream>
#include <stdlib.h>
#include<string>

using namespace std;

int main(){


    int i = 0 ;
    string sentence = "this is a sentence.";

    cout << "Input the string: \n";
    getline(cin, sentence);


    if( sentence[i] >= 'a' && sentence[i] <= 'z' )
        sentence[i++] -= 32 ;


    while ( i < sentence.size() )
    {
         if( sentence[i] == ' ' &&  sentence[i+1] >= 'a' && sentence[i+1] <= 'z' )
        {
            sentence[++i] -= 32 ;
        }
        ++i;
    }
    cout << "每個單字的第一個character都是大寫的句子為:\n";
    cout << sentence << endl;


    for (i = 0; i < sentence.size(); i++ )
    {   
        if ( sentence[i] >= 'a' && sentence[i] <= 'z' )
             sentence[i] -= 32;
    }

    cout << "所有characters都是大寫的句子為:\n";
    cout << sentence << endl;

 
    system("pause");
    return 0 ;
}

No comments:

Post a Comment