我有从标准例如装载有函数getline串的2D阵列:切割“ 0”从字符串
Hi my name is John.
I like chocolate.
然后,我想如果输入的字符串/子与串阵列示例的一个相匹配,以搜寻:
Ohn. - matches at line 1
chocolate. - matches at line 2
我使用的是非标准功能的strstr:
if ((strstr(array[i],string)) != NULL) {
printf("Match");
}
的问题是,当我想找到一个不在字符串末尾的字符串,就像我写的,它不匹配,因为可能当我想在字符串中找到“like”时,它可能与\“like”比较\ 0,所以它永远不会匹配。 (缓冲区)-1然后我分配内存为strlen(缓冲区) - 1 * sizeof(char),然后将它复制到与memcpy函数的数组。一切都工作正常,但是当字符串已经lenght 7-8它把2个未定义字符在字符串例子的末尾:
字符串与长度小于7或大于8个字符很好地工作。如果你知道如何解决这个问题或知道从字符串\ 0更好的方式只是字符串没有\ 0让我知道我会感激。
部分代码不起作用。只匹配像我提到的wtith结尾字符串.Pole是字符串的二维数组,行是存储字符串的缓冲区。
size_t len = 0;
char *line = NULL;
int number;
while ((number = getline(&line, &len, stdin)) != -1) {
for (i = 0; i < index; i++) {
if(strstr(pole[i], line) != NULL) {
printf("Match");
}
}
}
6
John.
'Hi my name is John.
' contain 'John.
'
'Testing stuff
' does not contain 'John.
'
'I do not know what to write
' does not contain 'John.
'
8
Testing
'Hi my name is John.
' does not contain 'Testing
'
'Testing stuff
' does not contain 'Testing
'
'I do not know what to write
' does not contain 'Testing
'
5
know
'Hi my name is John.
' does not contain 'know
'
'Testing stuff
' does not contain 'know
'
'I do not know what to write
' does not contain 'know
'
的字符串是一个数组以\ 0结尾的字符。如果它不以\ 0结尾,则不是字符串。此外,strstr不**计数\ 0。 – immibis
那么你能告诉我为什么它不匹配所有的字符串或子字符串? – paxie
你可以用你写的代码片段编辑问题吗? –