I am given the functions i need to use and i need to do the following things to
ID: 3547658 • Letter: I
Question
I am given the functions i need to use and i need to do the following things to any given string. I am looking for the C code to do these modifications to the strings. Thanks
void removeChars(char *str, const char *cs) - this function should modify the input
string, str to remove all instances of each character provided in the string cs and shift
any subsequent characters forward. For example, a call to this function on the strings
"Hello World", "ol" would result in the string "He Wrd"
void replaceChar(char *str, char c, char replace) - this function should modify the input
string str and replace any and all instances of the character in the variable c with the
character replace.
Explanation / Answer
#include <stdio.h>
#include <string.h>
void removeChars(char *str, const char *cs)
{
// set up the look-up table
int i, j;
int discard[256];
for (i = 0; i < 256; ++i)
discard[i] = 0;
for (i = 0; i < strlen(cs); ++i)
discard[cs[i]] = 1;
for (j = 0; j < strlen(str); ++j)
if (!discard[str[j]])
printf("%c", str[j]);
}
void replaceChar(char *str, char c, char replace)
{
int i;
for (i = 0; i < strlen(str); ++i) {
if(str[i] == c) str[i] = replace;
}
}
int main()
{
char str[] = "Hello World";
removeChars(&str[0], "ol");
printf(" ");
replaceChar(&str[0], 'd', 'e');
printf("%s ", str);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.