Home » Interview Questions » String Interview Questions » Remove spaces from a string

Remove spaces from a string


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


s  = “tu to rial cup”


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];
	//resizing the string, to print string without spaces
	//printing the string after removing spaces
int main()
	string s = "tu to rial cup";

Try It


How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Letter Case Permutation
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions