例如,我們有兩個字符串:關於產品的strcmp
string s = "cat";
string s1 = "dog";
是否正確寫出下面的方法?
int a = strcmp(s, s1);
或者什麼是正確的形式?
例如,我們有兩個字符串:關於產品的strcmp
string s = "cat";
string s1 = "dog";
是否正確寫出下面的方法?
int a = strcmp(s, s1);
或者什麼是正確的形式?
C++的std::string
可以直接比較,所以你可以寫例如
if (s == s1)
cout << "the strings are equal" << endl;
else if (s < s1)
cout << "the first string is smaller" << endl;
else
...
但是,如果您確實需要整數值,則可以使用the .compare
method。
int a = s.compare(s1);
只是爲了保持完整性,而當你有,你經常需要比較C風格空結尾的字符串到C++字符串常見的情況,你應該使用內置的字符串函數。例如,你會經常遇到系統調用返回一個指向C字符串的指針的情況。
您可以選擇關閉C-字符串轉換成C++字符串,並比較它們
string s1 = "cat";
string s2 = "dog";
const char *s3 = "lion";
if (s1 == string(s3))
cout << "equal" << endl;
else
cout << "not equal" << endl;
或C++的底層C字符串比較其他C-字符串:
a = strcmp(s1.c_str(), s3);
'STRCMP '是一個C庫函數 - 如果你正在編寫C++代碼,你通常會使用'string'類中的方法。 – 2010-07-10 08:15:07
我強烈建議在C++程序中使用C++字符串類。使用#include和std :: string。 –
shuttle87
2010-07-10 08:34:09