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

MessageQueue and Async / Await

c# message-queue async-await

I only want to receive my message in a async method! and its freezing my UI

How to remove polylines of google maps api 3

jquery google-maps-api-3

Can someone tell me why I can't remove my polylines with this code:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.