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

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



ссылка на сообщение  Отправлено: 07.11.14 08:36. Заголовок: C programming, deleting leading and trailing spaces


have to write a c program with a function called trim(). I am to use pointers to delete the spaces before and after the string that i pass, without deleting the spaces between the words. How would i go about doing this? I am not sure what would take away only the leading and trailing spaces.
-any help would be appreciated


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





ссылка на сообщение  Отправлено: 07.11.14 08:50. Заголовок: First of all take in..


First of all take into account that though the new line character '\n' is a white space character it shall not be deleted from a string even if it is a trailing character in a string. So you may not use function isspace. Instead you should apply standard function isblank if your compiler supports it. Otherwise you have to compare characters of the string with blank and tab characters yourself.

Here is a possible realization of the function within the demonstrative program
 
#include <stdio.h>
#include <string.h>
#include <ctype.h>


char * trim( char *s )
{
char *p = s;

while ( isblank( *p ) ) ++p;

char *q = p + strlen( p );

while ( q != p && isblank( *( q - 1 ) ) ) --q;

memcpy( s, p, q - p );

s[q - p] = '\0';

return s;
}


int main(void)
{
char s[] = " Hello lordcideon! ";

printf( "\"%s\"\n", s );
printf( "\"%s\"\n", trim( s ) );

return 0;
}

The output will be
 
" Hello lordcideon! "
"Hello lordcideon!"


If your compiler does not support function isblank then you should write explicitly for example
 
while ( *p == ' ' || *p == '\t' ) ++p;

instead of
 
while ( isblank( *p ) ) ++p;







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

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