Форум » C/C++ для начинающих (C/C++ for beginners) » string conversion » Ответить

string conversion

ascmax: I have exam coming up and have bunch of small exercises that have to be done. One of them is this, where I have no idea where to start. Implement function char* squeeze(const char* s) which would return a string containing the converted input string. Conversion should be done as shown in the example below: Input: AAABACCDDD Output: A3BAC2D3

Ответов - 2

Сыроежка: The declaration of the function [pre2] char * squeeze( const char *s ); [/pre2] 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 [pre2] #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; } [/pre2] The output is [pre2] AAABACCDDD A3BAC2D3 [/pre2] If you do no not know standard function std::distance then it can be simply changed to expression q - p. For example [pre2] size_t m = q - p; [/pre2] 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.

ascmax: Thank you very much !!! Now this is a lot of code I bet it is possible to make smaller program of this, because I have 45 of those exercises and those should be "small" tasks. At the moment I am stuck in the Bit Operations tasks. If I cant manage them, I will make a new post. Thank you again



полная версия страницы