c-在二维字符数组中搜索单词



给定一个大小为100x100个字符的2D数组和一个单词(1D字符数组(,在2D数组中查找给定单词的出现次数(仅从左到右水平搜索(。

char data[100][100] =
{
"ACFRTBOOK",
"BOPNBOOKQUIZGEEK",
"IDEQAPRACTICE"
};
char  Word[4] = "BOOK";

输出:

pattern found at 0, 5
pattern found at 1, 4

这可能会有所帮助:

int k = 0, n = 0;
char word[] = "BOOK";
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; data[i][j] != ''; j++)
{
n = j;
while (data[i][n] == word[k] && word[k] != '')
{
n++;
k++;
if (word[k] == '')
{
printf("Found at %i, %i", i, j)
}
}
k = 0;
}
}

首先,不能像对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
}
}

最新更新