code_junkie

How do I trim leading/trailing whitespace in a standard way?

Nov 11th, 2011
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.34 KB | None | 0 0
  1. char *trimwhitespace(char *str)
  2. {
  3. char *end;
  4.  
  5. // Trim leading space
  6. while(isspace(*str)) str++;
  7.  
  8. if(*str == 0) // All spaces?
  9. return str;
  10.  
  11. // Trim trailing space
  12. end = str + strlen(str) - 1;
  13. while(end > str && isspace(*end)) end--;
  14.  
  15. // Write new null terminator
  16. *(end+1) = 0;
  17.  
  18. return str;
  19. }
  20.  
  21. size_t trimwhitespace(char *out, size_t len, const char *str)
  22. {
  23. if(len == 0)
  24. return 0;
  25.  
  26. const char *end;
  27. size_t out_size;
  28.  
  29. // Trim leading space
  30. while(isspace(*str)) str++;
  31.  
  32. if(*str == 0) // All spaces?
  33. {
  34. *out = 0;
  35. return 1;
  36. }
  37.  
  38. // Trim trailing space
  39. end = str + strlen(str) - 1;
  40. while(end > str && isspace(*end)) end--;
  41. end++;
  42.  
  43. // Set output size to minimum of trimmed string length and buffer size minus 1
  44. out_size = (end - str) < len-1 ? (end - str) : len-1;
  45.  
  46. // Copy trimmed string and add null terminator
  47. memcpy(out, str, out_size);
  48. out[out_size] = 0;
  49.  
  50. return out_size;
  51. }
  52.  
  53. char *trim(char *str)
  54. {
  55. size_t len = 0;
  56. char *frontp = str - 1;
  57. char *endp = NULL;
  58.  
  59. if( str == NULL )
  60. return NULL;
  61.  
  62. if( str[0] == '' )
  63. return str;
  64.  
  65. len = strlen(str);
  66. endp = str + len;
  67.  
  68. /* Move the front and back pointers to address
  69. * the first non-whitespace characters from
  70. * each end.
  71. */
  72. while( isspace(*(++frontp)) );
  73. while( isspace(*(--endp)) && endp != frontp );
  74.  
  75. if( str + len - 1 != endp )
  76. *(endp + 1) = '';
  77. else if( frontp != str && endp == frontp )
  78. *str = '';
  79.  
  80. /* Shift the string so that it starts at str so
  81. * that if it's dynamically allocated, we can
  82. * still free it on the returned pointer. Note
  83. * the reuse of endp to mean the front of the
  84. * string buffer now.
  85. */
  86. endp = str;
  87. if( frontp != str )
  88. {
  89. while( *frontp ) *endp++ = *frontp++;
  90. *endp = '';
  91. }
  92.  
  93.  
  94. return str;
  95. }
  96.  
  97. int main(int argc, char *argv[])
  98. {
  99. char *sample_strings[] =
  100. {
  101. "nothing to trim",
  102. " trim the front",
  103. "trim the back ",
  104. " trim one char front and back ",
  105. " trim one char front",
  106. "trim one char back ",
  107. " ",
  108. " ",
  109. "a",
  110. "",
  111. NULL
  112. };
  113. char test_buffer[64];
  114. int index;
  115.  
  116. for( index = 0; sample_strings[index] != NULL; ++index )
  117. {
  118. strcpy( test_buffer, sample_strings[index] );
  119. printf("[%s] -> [%s]n", sample_strings[index],
  120. trim(test_buffer));
  121. }
  122.  
  123. /* The test prints the following:
  124. [nothing to trim] -> [nothing to trim]
  125. [ trim the front] -> [trim the front]
  126. [trim the back ] -> [trim the back]
  127. [ trim one char front and back ] -> [trim one char front and back]
  128. [ trim one char front] -> [trim one char front]
  129. [trim one char back ] -> [trim one char back]
  130. [ ] -> []
  131. [ ] -> []
  132. [a] -> [a]
  133. [] -> []
  134. */
  135.  
  136. return 0;
  137. }
  138.  
  139. void trim(char * s) {
  140. char * p = s;
  141. int l = strlen(p);
  142.  
  143. while(isspace(p[l - 1])) p[--l] = 0;
  144. while(* p && isspace(* p)) ++p, --l;
  145.  
  146. memmove(s, p, l + 1);
  147. }
  148.  
  149. char * trim(char * s) {
  150. int l = strlen(s);
  151.  
  152. while(isspace(s[l - 1])) --l;
  153. while(* s && isspace(* s)) ++s, --l;
  154.  
  155. return strndup(s, l);
  156. }
  157.  
  158. #ifndef STRLIB_H_
  159. enum strtrim_mode_t {
  160. STRLIB_MODE_ALL = 0,
  161. STRLIB_MODE_RIGHT = 0x01,
  162. STRLIB_MODE_LEFT = 0x02,
  163. STRLIB_MODE_BOTH = 0x03
  164. };
  165.  
  166. char *strcpytrim(char *d, // destination
  167. char *s, // source
  168. int mode,
  169. char *delim
  170. );
  171.  
  172. char *strtriml(char *d, char *s);
  173. char *strtrimr(char *d, char *s);
  174. char *strtrim(char *d, char *s);
  175. char *strkill(char *d, char *s);
  176.  
  177. char *triml(char *s);
  178. char *trimr(char *s);
  179. char *trim(char *s);
  180. char *kill(char *s);
  181. #endif
  182.  
  183. #include <strlib.h>
  184.  
  185. char *strcpytrim(char *d, // destination
  186. char *s, // source
  187. int mode,
  188. char *delim
  189. ) {
  190. char *o = d; // save orig
  191. char *e = 0; // end space ptr.
  192. char dtab[256] = {0};
  193. if (!s || !d) return 0;
  194.  
  195. if (!delim) delim = " tnf";
  196. while (*delim)
  197. dtab[*delim++] = 1;
  198.  
  199. while ( (*d = *s++) != 0 ) {
  200. if (!dtab[*d]) { // Not a match char
  201. e = 0; // Reset end pointer
  202. } else {
  203. if (!e) e = d; // Found first match.
  204.  
  205. if ( mode == STRLIB_MODE_ALL || ((mode != STRLIB_MODE_RIGHT) && (d == o)) )
  206. continue;
  207. }
  208. d++;
  209. }
  210. if (mode != STRLIB_MODE_LEFT && e) { // for everything but trim_left, delete trailing matches.
  211. *e = 0;
  212. }
  213. return o;
  214. }
  215.  
  216. // perhaps these could be inlined in strlib.h
  217. char *strtriml(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_LEFT, 0); }
  218. char *strtrimr(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_RIGHT, 0); }
  219. char *strtrim(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_BOTH, 0); }
  220. char *strkill(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_ALL, 0); }
  221.  
  222. char *triml(char *s) { return strcpytrim(s, s, STRLIB_MODE_LEFT, 0); }
  223. char *trimr(char *s) { return strcpytrim(s, s, STRLIB_MODE_RIGHT, 0); }
  224. char *trim(char *s) { return strcpytrim(s, s, STRLIB_MODE_BOTH, 0); }
  225. char *kill(char *s) { return strcpytrim(s, s, STRLIB_MODE_ALL, 0); }
  226.  
  227. void trim(char *str)
  228. {
  229. int i;
  230. int begin = 0;
  231. int end = strlen(str) - 1;
  232.  
  233. while (isspace(str[begin]))
  234. begin++;
  235.  
  236. while (isspace(str[end]) && (end >= begin))
  237. end--;
  238.  
  239. // Shift all characters back to the start of the string array.
  240. for (i = begin; i <= end; i++)
  241. str[i - begin] = str[i];
  242.  
  243. str[i - begin] = ''; // Null terminate string.
  244. }
  245.  
  246. void str_trim(char *output, const char *text, int32 max_len)
  247. {
  248. int32 i, j, length;
  249. length = strlen(text);
  250.  
  251. if (max_len < 0) {
  252. max_len = length + 1;
  253. }
  254.  
  255. for (i=0; i<length; i++) {
  256. if ( (text[i] != ' ') && (text[i] != 't') && (text[i] != 'n') && (text[i] != 'r')) {
  257. break;
  258. }
  259. }
  260.  
  261. if (i == length) {
  262. // handle lines that are all whitespace
  263. output[0] = 0;
  264. return;
  265. }
  266.  
  267. for (j=length-1; j>=0; j--) {
  268. if ( (text[j] != ' ') && (text[j] != 't') && (text[j] != 'n') && (text[j] != 'r')) {
  269. break;
  270. }
  271. }
  272.  
  273. length = j + 1 - i;
  274. strncpy(output, text + i, length);
  275. output[length] = 0;
  276. }
  277.  
  278. *
  279.  
  280. *
  281.  
  282. void inplace_trim(char* s)
  283. {
  284. int start, end = strlen(s);
  285. for (start = 0; s[start] && isspace(s[start]); ++start) {}
  286. if (s[start]) {
  287. while (end > 0 && isspace(s[end-1]))
  288. --end;
  289. }
  290. memmove(s, &s[start], end - start);
  291. s[end - start] = '';
  292. }
  293.  
  294. char* copy_trim(const char* s)
  295. {
  296. int start, end;
  297. for (start = 0; s[start] && isspace(s[start]); ++start) {}
  298. if (s[start] == '') return strdup("");
  299. for (end = strlen(s); end > 0 && isspace(s[end-1]); --end) {}
  300. return strndup(s + start, end - start);
  301. }
  302.  
  303. r = strdup(s + start);
  304. r[end-start] = '';
  305.  
  306. #include "stdafx.h"
  307. #include "malloc.h"
  308. #include "string.h"
  309.  
  310. int main(int argc, char* argv[])
  311. {
  312.  
  313. char *ptr = (char*)malloc(sizeof(char)*30);
  314. strcpy(ptr," Hel lo wo rl d G eo rocks!!! by shahil sucks b i g tim e");
  315.  
  316. int i = 0, j = 0;
  317.  
  318. while(ptr[j]!='')
  319. {
  320.  
  321. if(ptr[j] == ' ' )
  322. {
  323. j++;
  324. ptr[i] = ptr[j];
  325. }
  326. else
  327. {
  328. i++;
  329. j++;
  330. ptr[i] = ptr[j];
  331. }
  332. }
  333.  
  334.  
  335. printf("noutput-%sn",ptr);
  336. return 0;
  337. }
  338.  
  339. #include <ctype.h>
  340. #include <string.h>
  341.  
  342. /*
  343. Public domain implementations of in-place string trim functions
  344.  
  345. Michael Burr
  346. 2010
  347. */
  348.  
  349. char* ltrim(char* s)
  350. {
  351. char* newstart = s;
  352.  
  353. while (isspace( *newstart)) {
  354. ++newstart;
  355. }
  356.  
  357. // newstart points to first non-whitespace char (which might be '')
  358. memmove( s, newstart, strlen( newstart) + 1); // don't forget to move the '' terminator
  359.  
  360. return s;
  361. }
  362.  
  363.  
  364. char* rtrim( char* s)
  365. {
  366. char* end = s + strlen( s);
  367.  
  368. // find the last non-whitespace character
  369. while ((end != s) && isspace( *(end-1))) {
  370. --end;
  371. }
  372.  
  373. // at this point either (end == s) and s is either empty or all whitespace
  374. // so it needs to be made empty, or
  375. // end points just past the last non-whitespace character (it might point
  376. // at the '' terminator, in which case there's no problem writing
  377. // another there).
  378. *end = '';
  379.  
  380. return s;
  381. }
  382.  
  383. char* trim( char* s)
  384. {
  385. return rtrim( ltrim( s));
  386. }
  387.  
  388. #include <ctype.h>
  389.  
  390. void trim(char *a)
  391. {
  392. char *b = a;
  393. while (isspace(*b)) ++b;
  394. while (*b) *a++ = *b++;
  395. *a = '';
  396. while (isspace(*--a)) *a = '';
  397. }
  398.  
  399. /* See http://fctx.wildbearsoftware.com/ */
  400. #include "fct.h"
  401.  
  402. FCT_BGN()
  403. {
  404. FCT_QTEST_BGN(trim)
  405. {
  406. { char s[] = ""; trim(s); fct_chk_eq_str("", s); } // Trivial
  407. { char s[] = " "; trim(s); fct_chk_eq_str("", s); } // Trivial
  408. { char s[] = "t"; trim(s); fct_chk_eq_str("", s); } // Trivial
  409. { char s[] = "a"; trim(s); fct_chk_eq_str("a", s); } // NOP
  410. { char s[] = "abc"; trim(s); fct_chk_eq_str("abc", s); } // NOP
  411. { char s[] = " a"; trim(s); fct_chk_eq_str("a", s); } // Leading
  412. { char s[] = " a c"; trim(s); fct_chk_eq_str("a c", s); } // Leading
  413. { char s[] = "a "; trim(s); fct_chk_eq_str("a", s); } // Trailing
  414. { char s[] = "a c "; trim(s); fct_chk_eq_str("a c", s); } // Trailing
  415. { char s[] = " a "; trim(s); fct_chk_eq_str("a", s); } // Both
  416. { char s[] = " a c "; trim(s); fct_chk_eq_str("a c", s); } // Both
  417. }
  418. FCT_QTEST_END();
  419. }
  420. FCT_END();
  421.  
  422. static char const WHITESPACE[] = " tnr";
  423.  
  424. static void get_trim_bounds(char const *s,
  425. char const **firstWord,
  426. char const **trailingSpace)
  427. {
  428. char const *lastWord;
  429. *firstWord = lastWord = s + strspn(s, WHITESPACE);
  430. do
  431. {
  432. *trailingSpace = lastWord + strcspn(lastWord, WHITESPACE);
  433. lastWord = *trailingSpace + strspn(*trailingSpace, WHITESPACE);
  434. }
  435. while (*lastWord != '');
  436. }
  437.  
  438. char *copy_trim(char const *s)
  439. {
  440. char const *firstWord, *trailingSpace;
  441. char *result;
  442. size_t newLength;
  443.  
  444. get_trim_bounds(s, &firstWord, &trailingSpace);
  445. newLength = trailingSpace - firstWord;
  446.  
  447. result = malloc(newLength + 1);
  448. memcpy(result, firstWord, newLength);
  449. result[newLength] = '';
  450. return result;
  451. }
  452.  
  453. void inplace_trim(char *s)
  454. {
  455. char const *firstWord, *trailingSpace;
  456. size_t newLength;
  457.  
  458. get_trim_bounds(s, &firstWord, &trailingSpace);
  459. newLength = trailingSpace - firstWord;
  460.  
  461. memmove(s, firstWord, newLength);
  462. s[newLength] = '';
  463. }
  464.  
  465. int _tmain(int argc, _TCHAR* argv[])
  466. {
  467. FILE * fp; // test file
  468. char currDBSStatstr[100] = {"/0"};
  469. char *beg;
  470. char *end;
  471. char *str1;
  472. char str[] = "Initializing DBS Configuration";
  473. fp = fopen("file2-1.txt","r");
  474. if (fp != NULL)
  475. {
  476. printf("File exists.n");
  477. fgets(currDBSStatstr, sizeof(currDBSStatstr), fp);
  478. }
  479. else
  480. {
  481. printf("Error.n");
  482. exit(2);
  483. }
  484. //print string
  485. printf("String: %sn", currDBSStatstr);
  486. //extract first string
  487. str1 = strtok(currDBSStatstr, ":-");
  488. //print first token
  489. printf("%sn", str1);
  490. //get more tokens in sequence
  491. while(1)
  492. {
  493. //extract more tokens in sequence
  494. str1 = strtok(NULL, ":-");
  495. //check to see if done
  496. if (str1 == NULL)
  497. {
  498. printf("Tokenizing Done.n");
  499. exit(0);
  500. }
  501. //print string after tokenizing Done
  502. printf("%sn", str1);
  503. end = str1 + strlen(str1) - 1;
  504. while((end > str1) && (*end == 'n'))
  505. {
  506. end--;
  507. *(end+1) = 0;
  508. beg = str1;
  509. while(isspace(*str1))
  510. str1++;
  511. }
  512. printf("%sn", str1);
  513. if (strcmp(str, str1) == 0)
  514. printf("Strings are equal.n");
  515. }
  516. return 0;
  517.  
  518. Ustr *s1 = USTR1(7, " 12345 ");
  519.  
  520. ustr_sc_trim_cstr(&s1, " ");
  521. assert(ustr_cmp_cstr_eq(s1, "12345"));
  522.  
  523. const char *WHITESPACE=" tnr";
  524.  
  525. char *trimwhitespace(char *str)
  526. {
  527. int spacesAtStart = strspn(str, WHITESPACE);
  528. char *result = str + spacesAtStart;
  529. int lengthOfNonSpace = strcspn(result, WHITESPACE);
  530. result[lengthOfNonSpace] = 0;
  531. return result;
  532. }
Add Comment
Please, Sign In to add comment