Jump to content

  • Log In with Google      Sign In   
  • Create Account

String help in C


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
12 replies to this topic

#1 NUCLEAR RABBIT   Members   -  Reputation: 254

Like
0Likes
Like

Posted 16 April 2014 - 09:25 PM

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

Edited by NUCLEAR RABBIT, 16 April 2014 - 09:35 PM.

------------------------My band: RISE OVER ME!

Sponsor:

#2 frob   Moderators   -  Reputation: 22732

Like
3Likes
Like

Posted 16 April 2014 - 09:34 PM

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.


Check out my book, Game Development with Unity, aimed at beginners who want to build fun games fast.

Also check out my personal website at bryanwagstaff.com, where I write about assorted stuff.


#3 NUCLEAR RABBIT   Members   -  Reputation: 254

Like
0Likes
Like

Posted 16 April 2014 - 09:43 PM

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


------------------------My band: RISE OVER ME!

#4 georger.araujo   Members   -  Reputation: 824

Like
0Likes
Like

Posted 16 April 2014 - 10:10 PM

 

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.



#5 Álvaro   Crossbones+   -  Reputation: 13912

Like
3Likes
Like

Posted 17 April 2014 - 07:47 AM

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


#6 NightCreature83   Crossbones+   -  Reputation: 3033

Like
1Likes
Like

Posted 17 April 2014 - 08:25 AM

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, 17 April 2014 - 08:28 AM.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#7 georger.araujo   Members   -  Reputation: 824

Like
0Likes
Like

Posted 17 April 2014 - 09:05 AM

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



#8 Álvaro   Crossbones+   -  Reputation: 13912

Like
1Likes
Like

Posted 17 April 2014 - 09:19 AM

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



#9 NightCreature83   Crossbones+   -  Reputation: 3033

Like
-2Likes
Like

Posted 17 April 2014 - 10:51 AM

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, 17 April 2014 - 10:58 AM.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#10 Álvaro   Crossbones+   -  Reputation: 13912

Like
0Likes
Like

Posted 17 April 2014 - 11:15 AM


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.



#11 Álvaro   Crossbones+   -  Reputation: 13912

Like
0Likes
Like

Posted 17 April 2014 - 11:18 AM


    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.



#12 NightCreature83   Crossbones+   -  Reputation: 3033

Like
0Likes
Like

Posted 17 April 2014 - 11:27 AM

 


    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.


Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#13 Álvaro   Crossbones+   -  Reputation: 13912

Like
3Likes
Like

Posted 17 April 2014 - 11:35 AM

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





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS