Write a function "replace" which takes a pointer to a string as a parameter, which replaces all spaces in that string by minus signs, and delivers the number of spaces it replaced. Thus char *cat = "The cat sat"; n = replace( cat ); should set cat to "The-cat-sat" and n to 2.

Source Code

Brief explanation is provided after the source code.

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

int replace(char *);

int main(int argc, char ** argv) {
    int n;
    char *cat = "The cat sat down";

    n = replace(cat);
    printf(" and n to %d\n", n);
    return 0;
}

int replace(char *cat) {
    int n = 0, i;
    char buf[20];
    for(i = 0; i <= strlen(cat); i++) {
        if(isspace(cat[i])) {
            buf[i] = '-';
            n++;
        } else {
            buf[i] = cat[i];
        }
    }
    printf("\"%s\"", buf);
    return n;
}

When you compile and execute the above program it produces the following result on Linux:

 
"The-cat-sat-down" and n to 3

Brief Explanation

  • The program starts by initializing a pointer to a character array cat with string "The cat sat down".
  • The function replace takes the pointer to the string as a parameter and replaces all spaces in that string by minus signs, and delivers the number of spaces it replaced.
  • The return value of zero in the main function implies normal termination; non-zero values signal unusual or erroneous termination conditions.
  • The built-in function isspace declared in header ctype.h is used to check whether the passed character is white-space. If a white-space is found, it is replaced by a minus sign.
  • The character array buf is used to hold the new string with all white-space replaced by minus sign.
  • Using the printf functon, printf("\"%s\"", buf), the new string is printed to the standard output.

Add comment


Security code
Refresh