Solved

How to trim a string?

Posted on 2003-12-08
2
478 Views
Last Modified: 2010-04-01
We know in Java or in C# onecan trim a string. Is there any function which can do th same?

For example:

...
...
string s1;
...
...

in run time, s1 has a value of "hello world   ". I want to trim the spaces to have "hello world". Surely there many methods to do this. But I want a simple way.
0
Comment
Question by:chenwei
  • 2
2 Comments
 
LVL 44

Expert Comment

by:Karl Heinz Kremer
ID: 9895914
s1.erase ( s1.find_last_not_of (" ") + 1 ) ;

You can add more characters to the " " string, which specifies which characters to trim off the end. If you for example also want to trim tabs, use " \t".
0
 
LVL 44

Accepted Solution

by:
Karl Heinz Kremer earned 50 total points
ID: 9895934
BTW: If you also want to trim the string on the left side, there is also the find_first_not_of() method.
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question