Remove spaces from a string


StringViews 1978

Given a string, write a function that will print the given string without spaces

Example:

INPUT :
s  = “tu to rial cup”

OUTPUT :
“tutorialcup”

Time Complexity: O(n)

1. Traverse the string with two indexes ie, i for traversing and j for storing chars in output string

2. If we found a space in the string just ignore it, ie increament i but not j

3. If it is not a space store the character in output string ie, s[j] = s[i], increamnet i and j

C++ Program

#include <bits/stdc++.h>
using namespace std;


void printWithoutSpaces(string s)
{
	int n = s.length();
	int j =0;
	//traversing the string
	for (int i = 0; i < n; ++i)
	{
		if (s[i] != ' ')
		{
			s[j] = s[i];
			j++;
		}
	}
	//resizing the string, to print string without spaces
	s.resize(j);
	//printing the string after removing spaces
	cout<<s<<endl;
}
int main()
{
	string s = "tu to rial cup";
	printWithoutSpaces(s);
}

Try It

 

Translate »