-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathRemove spaces from string
39 lines (33 loc) · 1.22 KB
/
Remove spaces from string
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
A simpler but less efficient solution can be thought of as rearranging the characters everytime we encounter a space (O(n^2)).
But we move to a better solution which can solve it in O(n) time.
The idea is to keep track of count of non-space character seen so far.
1) Initialize 'count' = 0 (Count of non-space character seen so far)
2) Iterate through all characters of given string, do following
a) If current character is non-space, then put this character
at index 'count' and increment 'count'
3) Finally, put '\0' at index 'count'
#include <iostream>
using namespace std;
// Function to remove all spaces from a given string
void removeSpaces(char *str)
{
// To keep track of non-space character count
int count = 0;
// Traverse the given string. If current character
// is not space, then place it at index 'count++'
for (int i = 0; str[i]; i++)
if (str[i] != ' ')
str[count++] = str[i]; // here count is
// incremented
str[count] = '\0';
}
// Driver program to test above function
int main()
{
char str[] = "h ello there he llo ";
removeSpaces(str);
cout << str;
return 0;
}
Output:
hellotherehello