(Original delimiter) how to remove the blank before and after the string? (Use string. find_first_not_of, String. find_last_not_of) (C/C ++)

Source: Internet
Author: User

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 ++

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.