# String help in C

This topic is 1373 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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

#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;
}
Edited by NUCLEAR RABBIT

##### Share on other sites

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.

##### Share on other sites

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!

##### Share on other sites

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

#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.

##### Share on other sites

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;
}

##### Share on other sites
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

Edited by NightCreature83

##### Share on other sites
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...

##### Share on other sites
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).

##### Share on other sites

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.

Edited by NightCreature83

##### Share on other sites

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.

##### Share on other sites

    for (size_t counter = 0; counter < strlen(randomString); ++counter);

Oh, now this might take time that grows quadratically with the length of the string, depending on how smart the compiler is.

##### Share on other sites

    for (size_t counter = 0; counter < strlen(randomString); ++counter);

Oh, now this might take time that grows quadratically with the length of the string, depending on how smart the compiler is.

in release that should compile out, compilers are pretty good at seeing what is changing in a loop and what is not.

##### Share on other sites

    for (size_t counter = 0; counter < strlen(randomString); ++counter);

Oh, now this might take time that grows quadratically with the length of the string, depending on how smart the compiler is.

in release that should compile out, compilers are pretty good at seeing what is changing in a loop and what is not.

It's still good practice to write code so you don't have to trust the compiler to do something smart like that. In this case you just need to write
for (size_t counter = 0; randomString[counter] != '\0'; ++counter);