[英]How to find a char array in another one in c++?
I want to write a code to find a char array in another one and print out place(element) of first occur of first array. 我想编写一个代码在另一个数组中查找一个char数组,并打印出第一个数组的第一个出现的place(element)。 I wrote my own code and it works.
我编写了自己的代码,它可以工作。 But it "seems" kind of messy.
但是它“似乎”有点凌乱。 Does anyone have better idea to rewrite this code?
有谁有更好的主意来重写此代码?
"only strlen() is allowed. I need to write it by designing loops." “仅允许strlen()。我需要通过设计循环来编写它。”
Here's the code 这是代码
#include <iostream>
#include <string.h>
using namespace std;
const int len = 100;
int main() {
int i, j, k, l;
char a[len]="leonardo" , b[len]="nar";
bool es1 = false, es2=false;
i = 0;
while(i < len && !es1)
{
j = 0;
if(a[i] == b[j])
{
k = i+1;
l = j;
while (k < i+strlen(b) && !es2)
{
j = j+1;
if (a[k] == b[j]) k = k+1;
else es2 = true;
}
if (a[i+strlen(b)-1]==b[l+2] && !es2) es1 = true;
else i = i+1;
}
else i= i+1;
}
cout << endl << "element: " << i;
return 0;
}
By the way this not a real homework. 顺便说一句,这不是真正的作业。 I just make myself ready for a programming exam.
我只是准备参加编程考试。 I just find out that the code doesn't work fine if array b[] is shorter than 3 elements.
我只是发现,如果数组b []少于3个元素,则代码将无法正常工作。 So it seems the code needs major review!
因此,似乎代码需要进行重大审查!
The easy way to do it would be to use std::search
: 最简单的方法是使用
std::search
:
auto it = std::search(a, a + 8, b, b + 3));
Here, it
points to the beginning of the found sequence in a
, or to std::end(a)
if not found. 在这里,
it
指向发现序列的开始a
,或者到std::end(a)
如果没有找到。
Can you use a string instead of a char array? 可以使用字符串代替char数组吗? If so, you can use string::find.
如果是这样,您可以使用string :: find。
http://www.cplusplus.com/reference/string/string/find/ http://www.cplusplus.com/reference/string/string/find/
bool bFound = strA.find(strB)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.