Move the Spaces to Front of the String - String C Programs
Problem: Given a string that has set of words and spaces, write a program to move the spaces to front of string, you need to traverse the array only once and need to adjust the string in place.
1) Maintain two indices i and j.
2) Traverse from end to beginning.
If the current index contains char, swap chars in index i with index j.
This will move all the spaces to beginning of the array.
Read full article from Move the Spaces to Front of the String - String C Programs
Problem: Given a string that has set of words and spaces, write a program to move the spaces to front of string, you need to traverse the array only once and need to adjust the string in place.
1) Maintain two indices i and j.
2) Traverse from end to beginning.
If the current index contains char, swap chars in index i with index j.
This will move all the spaces to beginning of the array.
int main() |
{ |
char a[]= "Move space to begining" ; |
int n= strlen (a)-1,count = n; |
//MoveSpace(a,0,strlen(a)-1); |
for ( int i=n;i>=0;i--) |
{ |
if (a[i] != ' ' ) |
a[count--] = a[i]; |
} |
|
while (count>=0) |
a[count--] = ' ' ; |
cout << "After Space Moved to Begining" << a << endl; |
return 0; |
} |