C++ Program to Replace All Spaces in a String with %

This is a C++ Program to Replace all Spaces in a String with %.

Problem Description

The program takes a string and replaces all spaces in it with %.

Problem Solution

1. The program takes a string.
2. The string is checked for spaces and replaced with %.
3. The result is printed.
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Replace all Spaces in a String with %. The program output is shown below.

  1. #include<iostream>
  2. #include<string.h>
  3. using namespace std;
  4. int main ()
  5. {   
  6.     int i;
  7.     char str[50];
  8.     cout << "Enter string : ";
  9.     gets(str);
  10.     for (i = 0; str[i] !='\0'; i++)
  11.     {
  12. 	    if (str[i] == ' ')
  13.                 str[i]='%';
  14.     }			
  15.     cout << "Resultant string : " << str;
  16.     return 0; 
  17. }
Program Explanation

1. The program takes a string and stores it in the array ‘str’.
2. Using a for loop, the string is checked for spaces and replaced with ‘%’.
3. The result is then printed.

advertisement
Runtime Test Cases
Case 1 :
Enter string : Well begun is half done.
Resultant string : Well%begun%is%half%done.
 
Case 2 :
Enter string : Greece
Resultant string : Greece
 
Case 3 :
Enter string :12 23 34 45
Resultant string : 12%23%34%45

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

🔥 Enroll Now for Free Python Certification - December 2025

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.