Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
Problem Statement - Character replacements in a string
Write a c++ program to collect a small sentence from the user and then print the same sentence with all spaces replaced by hyphen (dash) character and all alphabets are replaced by their lower case counterparts.
Solution
TC++ #2673
Run Output
Input a small sentence:To get MOST out LIFE paddle SLOWLY.
The converted sentence is now = to-get-most-out-life-paddle-slowly.
#include <ctype.h> //This header is required to use function tolower() in this program
char sen[80]; cout<<“Input a small sentence:” ; cin.getline(sen,80);
User input sentence is collected in the character array.
for(int i=0;sen[i]!=”;i++) //Whole sentence is traversed till the null termination point { sen[i]=tolower(sen[i]);
Every character is converted to lowercase, this function automatically works on corresponding upper case character only so there is no need to check for character type.
if(sen[i]==’ ‘) sen[i]=’-‘;
If space character is found it is replaced by the hyphen (-) character. } cout<<“The converted sentence is now = ” <<sen<<endl; Final string is now printed.
Notes
Modern compilers prefer to use the library <cctype> instead of <ctype.h> for compatibility to unicode and all new language enhancements.