介绍
在C ++中比较字符串的技术 (Techniques to Compare Strings in C++)
Strings in C++ can be compared using either of the following techniques:
可以使用以下两种技术之一来比较C ++中的字符串:
String strcmp() function
字符串strcmp()函数
In-built compare() function
内置compare()函数
C++ Relational Operators ( ‘’ , ‘!=’ )
C ++关系运算符(’’,’!=’)
参考资料
笔记:
strcmp比较的是char * 类型的字符串
strcmp(s1, s2)
而
compare函数是string 的方法
s1.compare(s2)
string类型的变量还可以用
==来作为比较
string s1 = "aaa"; string s2 = "bbb"; s1 == s2;
注意:
char *类型的字符串只需要有效字符串长度相等即可,即如果\0
的长度不同并不影响判断。
而string类型需要字符串和长度都相等才行。
真题演练
下文是leetcode14题
注意双for循环中那个返回值,substr
方法目的就是裁剪去多余的零,从而满足机考判断。
class Solution014 {
public:
Solution014() {
cout << "Solution 014..." << endl;
}
string longestCommonPrefix(vector<string>& strs) {
if (!strs.size()) {
return "";
}
int str_length = strs[0].size();
int str_count = strs.size();
string res = string(str_length, 0);
for (int i = 0; i < str_length; ++i) {
char tmp = strs[0][i];
for (int j = 1; j < str_count; ++j) {
if (i == strs[j].size() || strs[j][i] != tmp) {
// return res.substr(0, i);
return res;
}
}
res[i] = tmp;
}
// return strs[0];
return res;
}
};