C ++ uses the substr () function to remove leading and trailing Spaces

Source: Internet
Author: User

Recently I made a question and encountered the problem of removing spaces before and after the string. In Java, there seems to be a string function that is trim (), which can eliminate spaces after the string. For C ++, check that a C ++ standard library boost can be referenced, which can be easily solved, but you need to download and set the environment variables, so you have not done it. Of course, you can also use regular expressions for matching, but it seems that all of them are useless. It is better to use the substr () function, and the string has the find_last_not_of, find_first_not_of and other attributes, which is enough for us to solve the problem.

# Include <iostream>
# Include <vector>
# Include <string>
# Include <fstream>
Using namespace STD;
// Read each row from the file, and eliminate leading and trailing spaces to create a new string.
Int main ()
{
String newstring = "";

Vector <string> STR;
Ifstream fin ("a.txt ");
String line;
While (Getline (FIN, line ))
Str. push_back (line );

For (unsigned I = 0; I <Str. Size (); I ++)
{
Newstring + = STR [I]. substr (STR [I]. find_first_not_of (""), STR [I]. find_last_not_of ("")-str [I]. find_first_not_of ("") + 1 );
}
Cout <newstring <Endl;
Return 0;
}

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/shuaiwang_01/archive/2008/11/01/3201560.aspx

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.