On-line: гостей 0. Всего: 0 [подробнее..]
Программисты всех стран, объединяйтесь!

АвторСообщение



ссылка на сообщение  Отправлено: 26.05.14 21:55. Заголовок: string conversion


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

Спасибо: 0 
ПрофильЦитата Ответить
Ответов - 2 [только новые]





ссылка на сообщение  Отправлено: 27.05.14 07:29. Заголовок: The declaration of t..


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.

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 27.05.14 11:30. Заголовок: Thank you very much ..


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

Спасибо: 0 
ПрофильЦитата Ответить
Ответ:
1 2 3 4 5 6 7 8 9
большой шрифт малый шрифт надстрочный подстрочный заголовок большой заголовок видео с youtube.com картинка из интернета картинка с компьютера ссылка файл с компьютера русская клавиатура транслитератор  цитата  кавычки моноширинный шрифт моноширинный шрифт горизонтальная линия отступ точка LI бегущая строка оффтопик свернутый текст

показывать это сообщение только модераторам
не делать ссылки активными
Имя, пароль:      зарегистрироваться    
Тему читают:
- участник сейчас на форуме
- участник вне форума
Все даты в формате GMT  3 час. Хитов сегодня: 5
Права: смайлы да, картинки да, шрифты да, голосования нет
аватары да, автозамена ссылок вкл, премодерация откл, правка нет