C + + use SUBSTR () function to eliminate the space before and after the solution of the _c language

Source: Internet
Author: User
Recently did a topic, encountered the details of the string to be removed before and after the space. In Java, there seems to be a string function that is trim () that eliminates the space after the string. For C + +, check it, you can refer to a C + + standard library boost, you can easily solve, but to download, set environment variables, so did not go to get. Of course, you can also use regular expressions to match, but it seems to be overqualified. Instead of using the substr () function, and the string has find_last_not_of,find_first_not_of, and so on, it's enough for us to solve the problem.
Copy Code code as follows:

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace Std;
Read each row from the file, and then remove the front and back spaces to connect to 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;
}

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.