Replacing Characters in C

This is part of a lab assignment

I have to implement the following function...

void replaceChar(char s[], char c,int len)

Description: Replace every character of s with c. len indicates the length of s.

I submit this to the autograder that my class uses and it tells me that "the length of the replaced string has different length." I have tested this extensively and do not see any issues. Here is my complete function:

void replaceChar(char s[], char c, int len) {
    printf("\n");
    for (int i = 0; i < len; i++) {
        s[i] = c;
        printf("%c",s[i]);
    }
}

I appreciate any help you can give me!

Here are a few of my test cases:

char s1[5] = {'h','e','l','l','o'};

char s3[10] = {'h','e','l','l','o',' ','h','i','i','i'};
char rep1 = 'x';
replaceChar(s1,rep1,5);
replaceChar(s3,rep1,10);

Answers


See my comment:

have you tried explicitly marking the NUL terminator? s[len] = '\0';

Though this corrects the issue, I'd still get in contact with your professors and ask them why this was necessary in the first place. The lab does not specify that the string s needs to be NUL-terminated.

As an aside (mentioned originally in another of my comments), you should take advantage of using string literals when initializing s1 and s3, i.e.

char s1[] = "hello";
char s3[] = "hello hiii";

This not only looks much cleaner (and avoids the need to explicitly mention the array length) but also guarantees the strings are NUL-terminated to begin with, too.


Need Your Help

Equivalent to WPF ControlTemplate.Triggers in silverlight

c# wpf xaml silverlight-4.0

The below is my WPF ControlTemplate.Triggers and i have changed the code in silverlight with the Interactivity.Interaction.Triggers and it is not working .

Building 32-bit Qt Mysql plugin fails with MinGw

mysql windows qt qt4 mingw

I'm building a MySQL plugin for Qt 4.4.3 Open Source Edition (Qt documentation), and using command: