It is very inefficient to define three character arrays to remove spaces from a string.
At least the array cc
char cc[30];
is in any case redundant.
In fact you are not removing spaces from a string. What you are doing is copying a string from one character array into another character array without spaces contained in the string.
In this for loop
for (j=0;j<i;j++){
if (c[j]==' ')
{
continue;
}
if (c[j]=='\0')
{
break;
}
ccc[j]=c[j];
}
you need to use a separate index for the character array ccc
. Otherwise it will contain indeterminate values that correspond to spaces in the array c
.
Pay attention to that usually when spaces are mentioned then they are meant two types of characters: the space character ' '
and the tab character '\t'
.
You could use standard algorithm std::remove
or std::remove_if
shown below.
However if you want to write yourself a similar algorithm for C strings then you could write a function the following way as shown in the demonstration program below.
#include <iostream>
#include <iomanip>
#include <cctype>
char * remove_blanks( char *s )
{
char *src = s, *dsn = s;
do
{
if (not std::isblank( ( unsigned char )*src ))
{
*dsn++ = *src;
}
} while (*src++);
return s;
}
int main()
{
char s[] = "\t1 2\t\t3 4 ";
std::cout << std::quoted( s ) << '\n';
std::cout << std::quoted( remove_blanks( s ) ) << '\n';
}
The program output is
" 1 2 3 4 "
"1234"
If your compiler does not support C++17 then instead of using the manipulator std::quoted
you could write for example
std::cout << '\"' << s << "\"\n";
Also instead of this if statement
if (not std::isblank( ( unsigned char )*src ))
where there is used the standard C function isblank
you could just write
if (*src != ' ' && *src != '\t' )
If to use standard algorithms then it will be enough to include headers <algorithm>
, <cstring>
and <cctype>
and to write either
std::remove( s, s + std::strlen( s ) + 1, ' ' );
or
std::remove_if( s, s + std::strlen( s ) + 1,
[]( unsigned char c ) { return std::isblank( c ); } );
Here is one more demonstration program.
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstring>
#include <cctype>
int main()
{
char s[] = "\t1 2\t\t3 4 ";
std::cout << std::quoted( s ) << '\n';
std::remove_if( s, s + std::strlen( s ) + 1,
[]( unsigned char c ) { return std::isblank( c ); } );
std::cout << std::quoted( s ) << '\n';
}
The program output is the same as shown above
" 1 2 3 4 "
"1234"