This is a common function in string processing ,. net Framework's string class directly provides trim () method, and most other languages also provide (VB, VFP ), however, no matter whether the standard library or STL can find the corresponding method, the following method is to remove STD from C ++ in the hope blog :: the space at the beginning and end of the string object is adapted, and the pass by reference is suitable for function usage. Among them, the find_first_not_of () and find_last_not_of () provided by STD: string are eye-opening. This method exists, I can find the first non-conforming position. I have never seen such a function in other languages.
1 /**/ /*
2 (C) oomusou 2006 Http://oomusou.cnblogs.com
3
4 Filename: stringtrim1.cpp
5 Compiler: Visual C + + 8.0
6 Description: Demo how to trim string by find_first_not_of & find_last_not_of
7 Release: 11/17/2006
8 */
9 # Include < Iostream >
10 # Include < String >
11
12 STD :: String & Trim (STD :: String & );
13
14 Int Main () {
15 STD :: String S = " Hello world !! " ;
16 STD: cout < S < " Size: " < S. Size () < STD: Endl;
17 STD: cout < Trim (s) < " Size: " < Trim (s). Size () < STD: Endl;
18
19 Return 0 ;
20 }
21
22 STD :: String & Trim (STD :: String & S) {
23 If (S. Empty ()) {
24ReturnS;
25}
26
27 S. Erase ( 0 , S. find_first_not_of ( " " ));
28 S. Erase (S. find_last_not_of ( " " ) + 1 );
29 Return S;
30 }
31
See also
(Original delimiter) how to remove the blank before and after the string? (Using template, you can go to whitespace) (C/C ++) (Template)
(Original blank) how to remove the blank spaces before and after the string? (C ++) (boost)
Reference
How to remove the spaces at the beginning and end of the STD: String object in C ++