给定一个大小为 100 x100 的字符的 2D 数组和一个单词(1D 字符数组),在 2D 数组中找到给定单词的出现次数(仅从左到右水平搜索)。
char data[100][100] =
{
"ACFRTBOOK",
"BOPNBOOKQUIZGEEK",
"IDEQAPRACTICE"
};
char Word[4] = "BOOK";
输出:
pattern found at 0, 5
pattern found at 1, 4
首先,您不能像使用char Word[4] = "BOOK";此操作那样将 char 数组初始化为 String,这必须char word[4] = {'b','o','o','k'};同样适用于您的 2D 数组命名数据。
所以这就是你将如何做这样的事情。我在//评论中添加了解释,但总体思路是将数组转换为字符串,因为在定位另一组字符时更容易使用。
如果您需要进一步的帮助,请告诉我。我希望这有帮助。
public void findWord(char[] word; char[][] data){
String w = new String(word); //it is much easier to work with strings for a searching problem like this
int x=0,y=0;
for(char[] i:data){//iterates through each row of data
String d = new String(i);
while(d.contains(w)){
x+=i.indexOf(w);//locates the pattern
System.out.println("pattern found at " + x + ", " + y);
x++;
d=s.substring(x);//this removes the previous occurance of the patern so that the index of can find a new repeat in the same row
}
y++;
x=0;//reset for next array
}
}
这可能会有所帮助:
int k = 0, n = 0;
char word[] = "BOOK";
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; data[i][j] != '\0'; j++)
{
n = j;
while (data[i][n] == word[k] && word[k] != '\0')
{
n++;
k++;
if (word[k] == '\0')
{
printf("Found at %i, %i", i, j)
}
}
k = 0;
}
}