我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置

I aim to write a program that will count and store the position of the occurence of a string within a character array

本文关键字:字符 字符串 存储 数组 位置 计算 目标 程序 一个 我的      更新时间:2023-10-16

程序将计算特定字符串在字符数组中出现的位置,并将该位置存储在数组中。例如,与字符串"hassan是一个麻烦者,麻烦者"相比,字符串"has"将位于位置[0,13,25,33]。正在使用两个主要字符数组;str[] 和子 []。str 是计算出现的字符串,并且子字符串比较。我已经附上了我对代码的想法。任何帮助都是值得赞赏的,因为我仍然是学生而不是专业人士,我非常感谢建设性的帮助,而不是评论我的代码和工作流程是如何草率的。我希望显示包含所有位置的数组,并且程序不显示返回值以外的任何内容,由于某些原因,返回值大多是非常大的数字。

#include <iostream>
#include <cstring>
using namespace std;
void allPositionsofSub()
{
int nstr;
int nsub;
char str[100];  //i initially wished to use the variable nstr but it wouldnt work with cin.get
char sub[nsub];
cout<<"Enter the string: ";
cin.get(str, 100);
cout<<"Enter the sub: ";
cin>>sub;
int num;
int count;
int count1=0;
int outdisplay[count];
for(int nstr1=0;nstr1<=99;nstr1++)
{
char n;
n = sub[nstr1];
while (nstr1<=nsub)
{
if (n==str[nstr1])
{
outdisplay[num]=nstr1;// this is where i think the problem perhaps lies.
num++;
count++;
}
}
}
while(count1<=count)
{
cout<<outdisplay[count1]<<", ";
count1++;
}
cout<<"-1";
}
int main()
{
allPositionsofSub();
}

更新的代码:

#include <iostream>
#include <cstring>
using namespace std;
void allPositionsofSub()
{
int nstr;
int nsub=20;
char str[100];
char sub[20];
cout<<"Enter the string: ";
cin.get(str, 100);
cout<<"Enter the sub: ";
cin>>sub;
int num;
int count;
int count1=0;
int outdisplay[count];
for(int nstr1=0;nstr1<=99;nstr1++)
{
char n;
n = sub[nstr1];
if (n==str[nstr1])
{
outdisplay[num]=nstr1;
num++;
count++;
}
}
while(count1<=count)
{
cout<<outdisplay[count1]<<", ";
count1++;
}
cout<<"-1";
}
int main()
{
allPositionsofSub();
}

因此,基本思想是枚举源字符串中的每个位置,并检查它是否是子字符串的开头。

您最好尝试实现以下伪代码,如果您还有其他问题,请回来。

# substr_len: The length of the substring you are looking for.
# str_len: The length of the source string.
# result: An array of int with sufficient length.
let match_count = 0
for (i in range 0..str_len-substr_len)
let match = true
for (j in range 0..substr_len-1)
if (substr[j] != str[i + j])
match = false
break
if (match)
result[match_count] = i
match_count = match_count + 1