Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a string [formating] ? c++

I want to truncate a string in a cout,

string word = "Very long word";
int i = 1;
cout << word << " " << i;

I want to have as an output of the string a maximum of 8 letters

so in my case, I want to have

Very lon 1

instead of :

Very long word 1

I don't want to use the wget(8) function, since it will not truncate my word to the size I want unfortunately. I also don't want the 'word' string to change its value ( I just want to show to the user a part of the word, but keep it full in my variable)

like image 915
Theriotgames Riot Avatar asked Oct 25 '13 04:10

Theriotgames Riot


1 Answers

I know you already have a solution, but I thought this was worth mentioning: Yes, you can simply use string::substr, but it's a common practice to use an ellipsis to indicate that a string has been truncated.

If that's something you wanted to incorporate, you could just make a simple truncate function.

#include <iostream>
#include <string>

std::string truncate(std::string str, size_t width, bool show_ellipsis=true)
{
    if (str.length() > width)
        if (show_ellipsis)
            return str.substr(0, width) + "...";
        else
            return str.substr(0, width);
    return str;
}

int main()
{
    std::string str = "Very long string";
    int i = 1;
    std::cout << truncate(str, 8) << "\t" << i << std::endl;
    std::cout << truncate(str, 8, false) << "\t" << i << std::endl;
    return 0;
}

The output would be:

Very lon...   1
Very lon      1
like image 174
Chris Olsen Avatar answered Sep 21 '22 16:09

Chris Olsen