String help in C

Started by
11 comments, last by alvaro 9 years, 12 months ago

Hello, I am trying to write a program that counts how many times a letter occurs in a string. I know there's easy ways to do it, but I want to use the strchr function to have a search key. I wrote this and for some reason, nothing even happens when I run it! No errors or nothing so I'm not sure what the problem could be! Any help is appreciated sad.png


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

int main(int argc, const char * argv[])
{
    const char * random_text = "Once there was this really old man who tranformed into dust. The end!";
    
    int counter = 0;
    int searchKey = 'd';
    char * strPtr = strchr(random_text, searchKey);
    
    do {
        if(strPtr != NULL)
           counter++;
        
        strPtr = strchr(random_text+1, searchKey);
    } while (strPtr != NULL);
    
    printf("%s\n%s\n\n%s%c%s%d%s", "The text:", random_text, "The occurence of ",
           searchKey, " happened ", counter, " times.\n");
    
    return 0;
}
Advertisement

Look more carefully at your loop. You are using strPtr to store the result, but using random_text to search on. You probably meant to assign the string to the pointer before the loop, and use strPtr as the parameter.

Look more carefully at your loop. You are using strPtr to store the result, but using random_text to search on. You probably meant to assign the string to the pointer before the loop, and use strPtr as the parameter.

ahhhhhhh, thank you!biggrin.png

Hello, I am trying to write a program that counts how many times a letter occurs in a string. I know there's easy ways to do it, but I want to use the strchr function to have a search key. I wrote this and for some reason, nothing even happens when I run it! No errors or nothing so I'm not sure what the problem could be! Any help is appreciated sad.png


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

int main(int argc, const char * argv[])
{
    const char * random_text = "Once there was this really old man who tranformed into dust. The end!";
    
    int counter = 0;
    int searchKey = 'd';
    char * strPtr = strchr(random_text, searchKey);
    
    do {
        if(strPtr != NULL)
           counter++;
        
        strPtr = strchr(random_text+1, searchKey);
    } while (strPtr != NULL);
    
    printf("%s\n%s\n\n%s%c%s%d%s", "The text:", random_text, "The occurence of ",
           searchKey, " happened ", counter, " times.\n");
    
    return 0;
}

I did it like this:


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

int main( int argc, const char * argv[] )
{
    char random_text[] = "Once there was this really old man who tranformed into dust. The end!";
    int counter = 0;
    int searchKey = 'd';
    char * strPtr = NULL;

    strPtr = strchr( random_text, searchKey );
    while ( strPtr != NULL )
    {
        counter++;
        strPtr = strchr( strPtr + 1, searchKey );
    }

    printf( "%s\n%s\n\n%s%c%s%d%s",
            "The text:", random_text,
            "The occurence of ", searchKey,
            " happened ", counter, " times.\n" );

    return 0;
}

Be careful when using string literals in C.

int count_instances_of_char(char const *string, char search_key) {
  int result;
 
  for (result = 0; (string = strchr(string, search_key)); ++result)
    ++string;
 
  return result;
}

std::string randomString = "Once there was this really old man who tranformed into dust. The end!";
size_t frequency[255];
ZeroMemory(frequency, 255 * sizeof(size_t))
for (size_t counter = 0; counter < randomString.size(); ++counter)
{
    ++frequency[randomString[counter]];
}
 
auto numberOfDs = frequency['d'];
//Same linear runtime but you have all of the frequencies of chars for the string, of course this only works for ASCII strings

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion


std::string randomString = "Once there was this really old man who tranformed into dust. The end!";
size_t frequency[255];
ZeroMemory(frequency, 255 * sizeof(size_t))
for (size_t counter = 0; counter < randomString.size(); ++counter)
{
    ++frequency[randomString[counter]];
}
 
auto numberOfDs = frequency['d'];
//Same linear runtime but you have all of the frequencies of chars for the string, of course this only works for ASCII strings

Really nice, provided that C++11 is an option for OP - I recall reading another topic he started where he made a question about a program in C as well.

Also, reading @Álvaro's elegant C code makes me realize just how rusty my own C is, and how glad I am to have put away my C hat...


std::string randomString = "Once there was this really old man who tranformed into dust. The end!";
size_t frequency[255];
ZeroMemory(frequency, 255 * sizeof(size_t))
for (size_t counter = 0; counter < randomString.size(); ++counter)
{
    ++frequency[randomString[counter]];
}
 
auto numberOfDs = frequency['d'];
//Same linear runtime but you have all of the frequencies of chars for the string, of course this only works for ASCII strings

The OP is using C, not C++. The OP said he wants to implement this using strchr. Your code invokes undefined behavior if one supplies a string with char values below 0 or above 254 (both of which can easily happen, even in platforms where BIT_CHAR is 8).

So here is a fixed up C version:


const char* randomString = "Once there was this really old man who tranformed into dust. The end!";
size_t frequency[256];
ZeroMemory(frequency, 256 * sizeof(size_t));
for (size_t counter = 0; counter < strlen(randomString); ++counter)
{
    ++frequency[(unsigned char)randomString[counter]];
}
 
size_t numberOfDs = frequency[(unsigned char)'d'];
//Same linear runtime but you have all of the frequencies of chars for the string, of course this only works for ASCII strings

All fixes to this code are trivial to transform from C++11 to C. You were right in the fact that i missed out one element in the frequency array and that you can have negative numbers in char, so the cast to unsigned char will fix this. And if we are going to exclude the use of ZeroMemory we can replace that with a memset which has a set value of 0.

In all fairness all I wanted to do is show a more generic solution to what was asked, which has a O(1) lookup at the end for all characters of a string.

Ow and if we are really honest here we are answering what is most likely a school assignment.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion


In all fairness all I wanted to do is show a more generic solution to what was asked, which has a O(1) lookup at the end for all characters of a string.

Yes, it's a good idea and I have used that kind of code in the past. If you had just described the idea, that would have been fine. But if you are going to post code, make sure its quality is good enough.


Ow and if we are really honest here we are answering what is most likely a school assignment.

Possibly, although I am not sure I care. At least the OP showed some effort. If he now understands what was wrong with his code and he learned a couple of other things from reading our solutions, I don't see anything wrong with the situation.

This topic is closed to new replies.

Advertisement