Advertisement

strchr question (C programming)

Started by April 27, 2014 08:51 PM
2 comments, last by NUCLEAR RABBIT 10 years, 9 months ago

Hello, so I was writing a program to print only words that end with "ed" and I thought that the last element in a char array was '\0' so I thought adding \0 to the end of the searchKey would help detect the end of the string but I guess I went about doing this wrong. What would you suggest I look into to accomplish what I'm trying to do?


#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, const char * argv[])
{
    char * lib[] = {"apple", "bat", "create", "destroy", "build"};
    int lib_size = sizeof(lib)/sizeof(lib[0]);
    char * searchKey = "b";
    char * wordPtr[lib_size];
    
    for(int i = 0; i < lib_size; i++)
    {
        wordPtr[i] = lib[i];
    }
    
    size_t searchSize = 1;
    
    printf("Word Bank:\n+ ");
    
    for(int i = 0; i < lib_size; i++)
    {
        printf("%s ", lib[i]);
    }
    
    printf("\n\nWords beginning with 'b':\n+ ");
    
    for(int i = 0; i < lib_size; i++)
    {
        if(strncmp(wordPtr[i], searchKey, searchSize) == 0)
        {
            printf("%s ", wordPtr[i]);
        }
    }
    
    //----------------------------------------------------------------
    
    printf("\n\nNew Word Bank:\n+ ");
    
    char * ed_lib[] = {"walke", "ededededs", "paniced", "play", "music", "education"};
    int ed_size = sizeof(ed_lib)/sizeof(ed_lib[0]);
    char * ed_searchKey = "ed\0";
    
    for(int i = 0; i < ed_size; i++)
    {
        printf("%s ", ed_lib[i]);
    }
    
    printf("\n\nWords ending in 'ed'\n+ ");
    
    char * edPtr = ed_lib;
    
    for(int j = 0; j < ed_size; j++)
    {
        edPtr = ed_lib[j];
        
        if(strstr(&edPtr[j], ed_searchKey) != NULL)
        {
            printf("%s ", ed_lib[j]);
        }
    }
    
    puts("");
    
    return 0;
}

The 0-character is used to indicate the end of the string, so your search key "ed\0" is interpreted as only "ed" because the hardcoded 0-character is interpreted as the end of the string. The fact that there's a second 0-character following your own is not something strstr is aware of.

As an alternative, don't search for the key at an arbitrary place. All you want to do is determine if a string ends in some particular way, so why search everywhere where it doesn't matter? Just look at the end of the string. For example: strcmp(ed_lib[j]+strlen(ed_lib[j])-2, "ed") or something along that line.

Advertisement

strstr(&edPtr[j], ed_searchKey)

should be:

strstr(edPtr, ed_searchKey)

The first begins searching at the jth character of the jth string in ed_lib.

thank you guys! biggrin.png

This topic is closed to new replies.

Advertisement