切割' \ 0'从字符串

时间:2015-12-08 08:21:32

标签: c string strstr

我有一个从stdin示例中加载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");
}

问题在于,当我想找到一个不像我写的字符串末尾的字符串时,它不匹配,因为可能当我想找到"喜欢"在字符串中它可能比较\ 0和"喜欢"所以它永远不会匹配。

当我用getline将行加载到缓冲区时我使用了函数:strlen(buffer)-1然后我为strlen(缓冲区)分配内存 - 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个字符的字符串可以正常工作。如果你知道如何解决这个问题或者知道一个更好的方法来制作字符串\ 0只是字符串没有\ 0让我知道我会很感激。

部分代码不起作用。只匹配我提到的wtith结束字符串.Pole是字符串的2D数组,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
'

2 个答案:

答案 0 :(得分:3)

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

"know\n" 

in

"I do not know what to write\n"

所以你的问题不是剥离\0字符串终止符,而是剥离\n行结尾。

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

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

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

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

答案 1 :(得分:0)

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

相关问题