1. 程式人生 > >把字串中的單詞首字母變成大寫

把字串中的單詞首字母變成大寫

總結:用有窮狀態自動機寫了個程式,算是對它的複習吧!~其實也是想試試。學到東西還是挺多的,flag標誌來控制是否的變成大寫,以及對非字元的處理狀態" NOUP ",對字元的處理“UP”又分兩類“大寫”和“小寫”。

#include<iostream>
#include<string>
#include<cctype>
using namespace std;

void upperTheFirstLetter(string &str) {
	const int BEGIN = 0;
	const int NOUP = 1;
	const int UP = 2;
	int STATE = BEGIN;
	unsigned int flag = 1;
	for (size_t i = 0; i < str.size(); i++) {
		switch(STATE){
			case BEGIN:
				if (isspace(str[i]) || ispunct(str[i])) {
					STATE = NOUP;
				}
				else if (islower(str[i])||isupper(str[i])) {
					STATE = UP;
					i--;
				}
				break;
			case NOUP:
				if (isspace(str[i]) || ispunct(str[i])) {
					STATE = NOUP;
				}
				else if (islower(str[i]) || isupper(str[i])) {
					STATE = UP;
					i--;
				}
				break;
			case UP:
				 if (isupper(str[i])) {
					STATE = UP;
					flag = 0;
				}
				else if (flag == 1) {
					str[i] = toupper(str[i]);
					flag = 0;
					STATE = UP;
				}
				else if (isspace(str[i]) || ispunct(str[i])) {
					STATE = NOUP;
					flag = 1;
				}

				break;
		}
	}
}
void main1() {
	string str1;
	getline(cin , str1);
	upperTheFirstLetter(str1);
	cout << str1 << endl;  
}