1

Using just C

I would like to parse a string and:

  1. count the occurrences of a character in a string (for example, count all the 'e's in a passed in string)
  2. Once counted (or even as I am counting) replace the e's with 3's
6
  • 3
    Sounds like homework. You should try to solve the problem yourself - it's very easy - and then ask questions here if you ruin into specific problems. Commented May 29, 2009 at 8:26
  • Homework thinks I. I'd use some kind of iteration mechanism (possibly a loop) to move through the string, checking each character as I pass it, incremening a count if it is the character I want, and replacing it with in the same operation. Commented May 29, 2009 at 8:28
  • 1
    @qrdl, it might be nice to ask before assuming it's homework. Commented May 29, 2009 at 8:48
  • 1
    @Walter, if this is indeed homework and you don't want the solution, please tag it as such. Being given solutions won't help you in the long term. And you should at least have a try first, you'll get more help that way (and learn faster). Commented May 29, 2009 at 8:52
  • Even if it isn't technically homework it calls for the homework framework - psudocode and ideas rather than the answer spelled out directly. Commented May 29, 2009 at 18:36

5 Answers 5

9

OK, you're either lazy, or stuck, assuming stuck.

You need a function with a signature something like

int ReplaceCharInString(char* string, char charToFind, char charThatReplaces)
{

}

Inside the function you need

  1. To declare an integer to count the occurrences
  2. A loop that moves from the start of the string to it's end
  3. inside the loop, an if statement to check is the current char the charToFind,
  4. statements to increment the count of occurrences and perform the replacement
  5. After the loop, you need to return the count of occurrences
Sign up to request clarification or add additional context in comments.

Comments

3

This function will take a string, replace every 'e' with '3', and return the number of times it performed the substitution. It's safe, it's clean, it's fast.

int e_to_three(char *s)
{
    char *p;
    int count = 0;
    for (p = s; *p; ++p) {
        if (*p == 'e') {
            *p = '3';
            count++;
        }
    }
    return count;
}

5 Comments

Because it's a solution for a homework question, I guess (no I wasn't the downvoter). Posting actually working code solutions for homework just encourages bad behaviour on part of lazy people :)
Upvoting since the homework tag wasn't in the original question, it was added by someone else.
Whether the homework tag is there or not, it isn't helpful to anyone (includingb the questioner) to give answers to these "post da codez pleez" type questions.
also, the solution is wrong I suppose what is the passed string is char * s = "Name"; in that case *p=3 will give an error as the "Name" string constant
Reply to let-them-c: char * s = "Name"; should be flagged as an error by your compiler, unless you turn the errors off.
2

Here's a shell to get you started. Ask here if you need any help.

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

int main(){
    const char* string = "hello world";
    char buffer[256];
    int e_count = 0;
    char* walker;

    // Copy the string into a workable buffer
    strcpy(buffer,string);

    // Do the operations
    for(walker=buffer;*walker;++walker){
        // Use *walker to read and write the current character
    }

    // Print it out
    printf("String was %s\nNew string is %s\nThere were %d e's\n",string,buffer,e_count);
}

Comments

2

In general, it's better use a standard library function rather than rolling your own. And, as it just so happens, there is a standard library function that searches a string for a character and returns a pointer to it. (It deals with a string, so look among the functions that have the prefix "str") (The library function will almost certainly be optimized to use specialized CPU opcodes for the task, that hand written code would not)

  1. Set a temp pointer (say "ptr") to the start of the string.

    • In a loop, call the function above using ptr as the parameter, and setting it to the return value.

    • Increment a counter.

    • Set the character at the pointer to "3" break when 'e' is not found.

Comments

2

Some of you guys are starting in the middle.

A better start would be

char *string = "hello world";
Assert(ReplaceCharInString(string, 'e', '3') == 1);
Assert(strcmp(string, "h3llo world") == 0);

7 Comments

This is presumably a suggestion to write the test first. It is interesting but I'm not sure that it's the best technique for writing with pointer-heavy code in C, because of the unpredictable and unrepeatable effects of incomplete code.
@Edmund I'd be interested to know why that might be the case. At the very least the tests specify what the routine is to do, and confirms it does so
I think the tests are useful, but I think the pain of writing them and getting them working from scratch is more in C than in non-pointery languages and hence the benefit of TDD is diminished. If it fails non-gracefully, it's much harder to know why. If it passes, it might still have disrupted things for other tests.
I can't say that has been my experience, but maybe it depends what sort of code is being written
I've done some TDD in C, and it works perfectly fine. I think if you've worked in C, you learn to be careful with NULL and uninitialized local variables. You'll do a lot of "AssertNotNull()" in your tests. Then you mostly worry about infinite loops and walking off the end of buffers. The former locks up your test suite in any language; the latter is a crash in C instead of an exception, but isn't really that common.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.