Force std::string Width

M

Mike Copeland

Is there any std::string function that will either force the value of
a variable to be no more than a maximum number of characters or fill it
if it's less? For example:

std::string someStr1 = "The Phantom Spitter was here.";

where I want 20, but _no more_ than 20, characters to be displayed. But
with:

std::string someStr2 = "Kilroy here.";

I want the output display to be 20 characters.
In other words, I want a substr of a string value if it's >20
characters, but I want to have the value "padded" when it's less than 20
characters. I know that setw() will pad/fill the data, but is there
something that will either fill or truncate a string to a specified
length, depending on its length? TIA
 
J

Juha Nieminen

red floyd said:
Oh, that's a nice one! I'll have to remember that one!

Was that sarcasm? It's doing the same thing as s.resize(20, ' '), just
a lot less efficiently.
 
R

red floyd

Was that sarcasm? It's doing the same thing as s.resize(20, ' '), just
a lot less efficiently.

Actually, no. It's been a while since I've done some serious C++
(currently mostly C) and I'm a bit rusty. I had completely forgotten
resize.
 
J

Juha Nieminen

red floyd said:
Actually, no. It's been a while since I've done some serious C++
(currently mostly C) and I'm a bit rusty. I had completely forgotten
resize.

Admittedly the line is "clever" in that it demonstrates many of the
features of std::string (in particular, and C++ in general). However,
one should always know what is and isn't efficient, and if there might
be a better way of doing it (in this particular case the better way is
not only more efficient, but also shorter and simpler).

(C++11 might make that line of code slightly more efficient thanks to
move constructors, but it will still be significantly less so than a
simple resize.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top