这对我来说真的很难,我该怎么办
this is really hard for me, and what should i do?
我的问题在C 中。如何比较两个不同的长度字符串。例如string a = "ap"
string b = "apple"
。因此,最后一场比赛应该是1,或考虑另一个示例,例如string a = "123"
string b = "123123123"
,最后一场比赛应为3。因此,我认为我尝试让a[i]= b[i]
,但仅比较1个charcater。如何比较muliple长度字符串。
int getMatchCount(string a, string b)
{
int match = 0;
if (a.length() == 0 or b.length() == 0 )
{
return -1;
}
for (int i = 0; i < a.length(); i++)
{
if( string.compare(a, b) )
{
match = match +1;
}
}
return match;
}
这是一个天真的,但可行的解决方案:
#include <iostream>
#include <string>
#include <algorithm>
int main(int argc, const char * argv[]) {
std::string first = "hello";
std::string second = "hello_world";
int match = 0;
for (int i = 0; i < std::min(first.length(), second.length()); ++i) {
if(first.at(i) == second.at(i)) {
match++;
} else {
break;
}
}
std::cout << match << std::endl;
return 0;
}
因为请求:
#include <algorithm>
在那里用于std::min()
功能,以避免访问无效的内存地址。也就是说,它可以防止for
循环访问大于string.length()
的任何string
索引,这将导致不确定的行为...或者在我学习C 时返回segmentation fault
。
在这种情况下,它已被某些逻辑和短手三元运算符替换。
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
string first = "hello";
string second = "hello_world";
int match = 0;
size_t lowest = first.length() <= second.length() ? first.length() : second.length();
for (int i = 0; i < lowest; ++i) {
if(first.at(i) == second.at(i)) {
match++;
} else {
break;
}
}
cout << match << endl;
return 0;
}
使用std::string::find
#include <iostream>
int getMatchCount(std::string a, std::string b)
{
int match = 0;
std::size_t pos = 0;
while ((pos = b.find(a, pos)) != std::string::npos) {
++pos;
++match;
}
return match;
}
int main() {
std::cout << getMatchCount("is", "isis");
return 0;
}
编辑我使用std::size_t
,因为我想将其与std::string::npos
进行比较。int不能保证足够大,无法做到这一点。std::size_t
也是未签名的,这使其成为表示索引的好选择。
如果我们分解循环,它将运行b.find(a, pos)
,这将在字符串b
中找到子字符串a
的第一次发生。如果找到匹配项,则返回值是子字符串启动的索引,或者如果找不到 std::string::npos
。
第一次运行 pos
是 0
,因此我们从搜索时从字符串B的开头开始。然后,我们将返回的值存储在pos
中。(在我们的示例中,第一次比赛将再次是0
(
如果返回值不是std::string::npos
,我们找到了匹配项,因此我们增加了match
。对于循环的下一次迭代,我们希望在上一场比赛之后启动搜索,因此我们将pos
递增。(在我们的示例中,我们将其增加到1,然后搜索从索引1及以前开始的子字符串(
- 我的 cout 上有一个奇怪的输出,它把答案放在第一位,然后在我调用它的地方放一个奇怪的输出.我该怎么办?
- 当两个相等的双精度的相对比较不起作用时,我该怎么办?
- 我需要通过窗口句柄(HWND)获取文件,我该怎么办?
- 我正在"void value not ignored as it ought to be"我该怎么办?
- 未定义的引用错误,我该怎么办?
- 我在此代码中要求一个数字,如果用户给出一个字母,我该怎么办?
- 当一个功能完成另一个功能打开时,我该怎么办?
- 如果我尝试将 graphics.h 用于 c/c++ 时显示错误,我该怎么办?
- 这对我来说真的很难,我该怎么办
- 在C 中,我该怎么办才能格式化输出
- 当MPI中未知的发送消息数量时,我该怎么办
- 如果违反了利斯科夫替代原则,我该怎么办?
- 当(CUDA 7.5的)nvcc / cudafe++崩溃并出现段错误时,我该怎么办?
- 当来自外部库的线程不可预测地崩溃我的应用程序时,我该怎么办
- C++ 中的整数范围 - 当标准尚不存在时我该怎么办
- 很难我的代码
- Visual Studio C++:获取未解析的令牌和未解析的链接.我该怎么办
- qextserialport在Windows上丢弃数据——我该怎么办
- 函数内存不足-我该怎么办
- 此代码显示错误"stu undeclared" ??我该怎么办