In: Computer Science
Write a short program that asks the user for a sentence and prints the result of removing all of the spaces. Do NOT use a built-in method to remove the spaces. You should programmatically loop through the sentence (one letter at a time) to remove the spaces.
C++ program:
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
cout<<"Enter a String of your
choice"<<endl;
string s;
getline(cin, s);
int n = s.length(); // find length of string
/*convert String into String array*/
char string_array[n + 1];// declare String array
s.copy(string_array, s.size() + 1); // copy string into String
array
string_array[s.size()] = '\0'; // enter \0 at the end of string
array
/*Removing Spaces*/
int i = 0, j = 0;
while (string_array[i]) // while loop till end of the string
{
if (string_array[i] != ' ') { // condition to remove string
// if no space then put it into array otherwise
left it
// if there is space then condition is fail and
increment i
// and check for another charector
string_array[j++] = string_array[i];
}
i++;
}
string_array[j] = '\0'; // add '\0' at the end of string
cout<<"String with no whitespace
:"<<string_array<<endl; // print String
return 0;
}
Output 1:
Output 2:
Program Snapshot
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
cout<<"Enter a String of your choice"<<endl;
string s;
getline(cin, s);
int n = s.length(); // find length of string
/*convert String into String array*/
char string_array[n + 1];// declare String array
s.copy(string_array, s.size() + 1); // copy string into String array
string_array[s.size()] = '\0'; // enter \0 at the end of string array
/*Removing Spaces*/
int i = 0, j = 0;
while (string_array[i]) // while loop till end of the string
{
if (string_array[i] != ' ') { // condition to remove string
// if no space then put it into array otherwise left it
// if there is space then condition is fail and increment i
// and check for another charector
string_array[j++] = string_array[i];
}
i++;
}
string_array[j] = '\0'; // add '\0' at the end of string
cout<<"String with no whitespace :"<<string_array<<endl; // print String
return 0;
}