1. 程式人生 > >C++primer第五版 編寫一段程式讀入兩個字串,比較其是否相等並輸出結果。如果不相等,輸出較大的那個字串和長度較大的那個字串

C++primer第五版 編寫一段程式讀入兩個字串,比較其是否相等並輸出結果。如果不相等,輸出較大的那個字串和長度較大的那個字串

一個字串比較的簡單程式。

string物件相等意味著它們的長度相同且所包含的字元也全都相同。
字串的比較:
1.如果兩個string物件的長度不同,而且較短string物件的每個字元都與較長string物件對應位置上的字元相同,就說string物件小於較長string物件
2.如果兩個string物件在某些對應的位置上不一致,則string物件比較的結果其實是string物件中第一對相異字元比較的結果。 

// primer_3_2_2.cpp : Defines the entry point for the application.
// 編寫一段程式讀入兩個字串,比較其是否相等並輸出結果。如果不相等,輸出較大的那個字串和長度較大的那個字串

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

int main()
{
	string str1,str2;
	cout << "input two strings: " << endl;
	cin >> str1 >> str2;
	//getline(cin,str1);
	//getline(cin,str2);
	if(str1==str2)
		cout << "the two strings are equal." << endl;
	else
	{
		if(str1>str2)
			cout << '"' << str1 << '"' << "is greater than" << '"' << str2 << '"' << endl;
		else
			cout << '"' << str2 << '"' << "is greater than" << '"' << str1 << '"' << endl;
		if(str1.size()>str2.size())
			cout << '"' << str1 << '"' << "is longer than" << '"' << str2 << '"' << endl;
		else
		{
			if(str2.size()>str1.size())
				cout << '"' << str1 << '"' << "is longer than" << '"' << str2 << '"' << endl;
			else
				cout << "the two strings of " << "'" << str1 << "'" << " and " << "'" << str2 << "'" << " have the same length " << endl;
	
		}
	}
	system("pause");
	return 0;
}

在“input two strings”的提示下,輸入

hello

better

敲回車,就會出現以下結果:

注意,用cin讀入字串時,是不能有空格的,如果出現空格,便會當成兩個字串處理,例如輸入“hello world”,它就會自動將“hello”賦給str1,將“word”賦給str2。例如

如果我們需要比較一行字串,則應該使用getline函式。 即將cin行程式碼註釋掉,將getline兩行程式碼解註釋,如下:

//cin >> str1 >> str2;
getline(cin,str1);
getline(cin,str2);

但是這裡要提醒一下,getline將換行符也讀進來了,因此輸入兩行字串後敲回車並不會立刻產生結果,需要再敲一個回車才能打印出來。例如