The declaration of the function
char * squeeze( const char *s );
means that inside the function there must be a dynamically allocated new string. To allocate the string (that is a character array) you need to determine its length.
So at first you determine the length of the resulted string, allocate it, and then form it according to the assignment.
If the code may be written in
C++ you can use standard algorithm
std::find_if Here is the function
#include <iostream>
#include <algorithm>
#include <iterator>
#include <functional>
#include <cstring>
#include <cstdio>
#include <cassert>
char * squeeze( const char *s )
{
size_t n = std::strlen( s ) + 1;
size_t i = 0;
const char *p = s;
while ( p != s + n )
{
const char *q = std::find_if( p, s + n,
std::bind2nd( std::not_equal_to<char>(), *p ) );
size_t m = std::distance( p, q );
if ( m != 1 )
{
do { ++i; } while ( m /= 10 );
}
++i;
p = q;
}
char *s1 = new char[ i ];
char *t = s1;
p = s;
while ( p != s + n )
{
*t++ = *p;
const char *q = std::find_if( p, s + n,
std::bind2nd( std::not_equal_to<char>(), *p ) );
size_t m = std::distance( p, q );
if ( m != 1 )
{
t += std::sprintf( t, "%u", m );
}
p = q;
}
assert( std::strlen( s1 ) + 1 == i );
return ( s1 );
}
int main()
{
const char s[] = "AAABACCDDD";
std::cout << s << std::endl;
char *s1 = squeeze( s );
std::cout << s1 << std::endl;
delete [] s1;
return 0;
}
The output is
AAABACCDDD
A3BAC2D3
If you do no not know standard function
std::distance then it can be simply changed to expression
q - p. For example
size_t m = q - p;
You can also write your own loop instead of the algorithm
std::find_if that to find a character that is not equal to the given character in the string.