[topic] 末尾の空白文字を取り除く

与えられた文字列の末尾の空白文字を取り除く方法と、その操作が与えられた文字列を破壊するかどうか。取り除かれる空白文字の種類。

Posted feedbacks - C

Cがなかったので。 正規表現でやると、こんな感じでしょうか。。。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <string.h>
#include <regex.h>

void rstrip( char* dest, const char* src ) {
  regex_t preg;
  regmatch_t pmatch;
  
  regcomp(&preg, "\\ +$", REG_EXTENDED|REG_NEWLINE);
  regexec(&preg, src, 1, &pmatch, 0);
  regfree(&preg);
  
  strncpy( dest, src, pmatch.rm_so );
}

組み込みではないので自作で破壊的関数。
空白文字の判定は isspace を使っていますが、取り除かれる文字は ASCIIコードで [9, 10, 11, 12, 13, 32]。
1
2
3
4
5
6
7
8
9
#include <ctype.h>
char* rtrim( char *str ){
   char *p = str;
   while( *p++ );
   p--;
   while( isspace( *(--p) ) );
   *(p+1) = '\0';
   return str;
}

マイナス評価を付けても反応が無かったので、ちゃんと指摘します。
次のような場合|123  |と出力されず、|123|と出力されます。文字列が空白だけの時は...((((;゜Д゜)))
 char s[] = "123       ";
 rtrim(s + 5);
 printf("|%s|\n", s);

Index

Feed

Other

Link

Pathtraq

loading...