Question

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);
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top