gpt4 book ai didi

c++ - string1 == string2和您自己的for循环比较之间有什么区别?

转载 作者:行者123 更新时间:2023-12-01 15:07:53 26 4
gpt4 key购买 nike

假设您要比较C++中的两个字符串以查看它们是否相同。除了打字更少之外,以下内容之间是否还有其他区别?一个比另一个快吗?还有比这里包含的更好的比较字符串的方法吗?

版本A:if( string1 == string2 ) { return true; }
版本B:

// Check for equal length, then...
for( int i = 0; i < string1.length(); ++i ) {
if( string1[i] != string2[i] ) { return false; }
}
return true;

最佳答案

Is there any difference between the following?



是。您的代码不会检查字符串的长度,因此,如果第一个字符串长于第二个字符串,您最终可能会在第二个字符串的末尾读取。如果第一个字符串是第二个字符串的适当前缀,则您的代码将返回错误的结果。

Is one faster than the other?



使用标准库函数可能与您自己的函数相同或更快,因为可以更好地优化标准库函数。例如, ==运算符可能使用 std::memcmp一次比较多个字符。

Is there a better way to compare the strings than what is contained here?



不,不是。就简单性和速度而言, string1 == string2可能和它一样好。

关于c++ - string1 == string2和您自己的for循环比较之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62295894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com