从字符串中剪切“\0”

Cutting ' \0' from strings

我有一个二维字符串数组,其中加载了标准输入示例中的 getline :

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[=31=] 与 "like" 进行比较,因此它永远不会匹配。

当我使用 getline 将行加载到缓冲区时,我使用了函数:strlen(buffer)-1 然后我为 strlen(buffer) - 1 * sizeof(char) 分配了内存,然后使用 memcpy 函数将其复制到数组.一切正常,但是当字符串的长度为 7-8 时,它会在字符串示例的末尾放置 2 个未定义的字符:

Enter string :testtttt
memcpy to allocated array of strlen(string) - 1
printed string from array looks like : testttttt1� or testtttttqx etc..

长度小于 7 个或大于 8 个字符的字符串都可以正常工作。如果您知道如何解决此问题或知道更好的方法来从 string[=32=] 制作不带 \0 的字符串,请告诉我,我将不胜感激。

部分代码无效。仅与结尾字符串匹配,例如 i mentioned.Pole 是二维字符串数组,line 是存储字符串的缓冲区。

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
'

您的问题在调试输出中很明显。 getline 不会从输入中删除换行符,因此例如您正在搜索:

"know\n" 

"I do not know what to write\n"

所以你的问题不是剥离 [=15=] 字符串终止符,而是剥离 \n 行尾。

这可以通过多种方式实现,例如:

char* newline = strrchr( line, '\n' ) ;
if( newlineaddr != NULL )
{
    *newlineaddr  = '[=12=]' ;
}

size_t newlineindex = strcspn(line, "\n") ;
line[newlineindex] = '[=13=]' ;

第一个处理多行输入(在这种情况下不需要)- 只删除最后一个换行符,而第二个更简洁。

通过 c 中的函数搜索非常 easy.You 可以使用 strcmp 进行比较,strcmp 带有不同的风格,如 stricmp、strncmp 等等...这是 link