C Program to Replace Spaces By *

Problem:

Write a C program to replace spaces by * or star. Write a program which accepts a sentence from the user and alters it as follows:
Every space is replaced by *,case of all alphabets is reversed, digits are placed by ?

Note: Instead of fgets() you can use gets() function. But it may cause buffer overflow.

Algorithm or Solution:

Here is the algorithm or logical solution of C program to replace spaces by *, to replace digits by ? and to reverse the cases of alphabets.
  1. Star
  2. Accept a sentence as string.
  3. To replace space, use if statement to compare corresponding character of string and space in single quotes, if is it space replace it with *.
  4. Next check if the character is in lower case by using islower() function of ctype.h header file, if yes then change it to upper case with toupper() function of ctype.h header file otherwise change to lower case using tolower() function.
  5. Check if the character is digit by using isdigit() function of ctype.h header file, if yes then replace that digit with '?'.
  6. Display the altered sentence.
  7. Stop.

C Program / Source Code:

Here is the source code of C program to replace spaces by * or star.
/* Aim: Write a C program to replace spaces by * or star, to replace digits by ?,
 to reverse the cases of alphabets.*/

#include<stdio.h>
#include<ctype.h>
#include<string.h>
#define size 100

void Stral(char str[]); // Stral Function Prototype

int main()
{
 char str[size];
 
 printf("\n Enter any sentence:-");
 fgets(str,size,stdin);

 Stral(str);

 return 0;

} // End of main() function

// Stral Function to replace spaces by * or star
void Stral(char str[])
{
 int i,j=0;

 // To replace space by * in sentence
 for(i=0;i<=strlen(str)-1;i++)
 { 
 if(str[i]==' ')
  str[i]='*';

 // To change the case of alphabets in sentence
 if(islower(str[i]))
  str[i]=toupper(str[i]);
 else
  str[i]=tolower(str[i]);

 // To replace digits by ? in sentence
 if(isdigit(str[i]))
  str[i]='?';
 }
 
 printf("\n %s \n",str);

} // End of Stral Function

/* Output of above code:-

 Enter any sentence:-hi i am master chief 343

 HI*I*AM*MASTER*CHIEF*???

*/