Domanda

Sto usando std::string e la necessità di pad lasciato loro per una data larghezza. Qual è il metodo consigliato per fare questo in C ++?

ingresso Esempio:

123

pad a 10 caratteri.

Esempio di output:

       123

(7 posti di fronte a 123)

È stato utile?

Soluzione

std :: setw (setWidth) manipolatore

std::cout << std::setw (10) << 77 << std::endl;

o

std::cout << std::setw (10) << "hi!" << std::endl;

uscite imbottiti 77 e "hi!".

se avete bisogno di portare come esempio l'uso di stringa di std :: stringstream invece std :: cout oggetto.

ps: file di intestazione responsabile <iomanip>

Altri suggerimenti

void padTo(std::string &str, const size_t num, const char paddingChar = ' ')
{
    if(num > str.size())
        str.insert(0, num - str.size(), paddingChar);
}

int main(int argc, char **argv)
{
    std::string str = "abcd";
    padTo(str, 10);
    return 0;
}

Si può usare in questo modo:

std::string s = "123";
s.insert(s.begin(), paddedLength - s.size(), ' ');

Il modo più semplice che posso pensare sarebbe con uno stringstream:

string foo = "foo";
stringstream ss;
ss << setw(10) << foo;
foo = ss.str();

foo dovrebbe ora essere imbottito.

è possibile creare una stringa contenente N spazi chiamando

string(N, ' ');

Quindi, si potrebbe fare in questo modo:

string to_be_padded = ...;
if (to_be_padded.size() < 10) {
  string padded(10 - to_be_padded.size(), ' ');
  padded += to_be_padded;
  return padded;
} else { return to_be_padded; }
std::string pad_right(std::string const& str, size_t s)
{
    if ( str.size() < s )
        return str + std::string(s-str.size(), ' ');
    else
        return str;
}

std::string pad_left(std::string const& str, size_t s)
{
    if ( str.size() < s )
        return std::string(s-str.size(), ' ') + str;
    else
        return str;
}

C'è un modo piacevole e semplice :)

const int required_pad = 10;

std::string myString = "123";
size_t length = myString.length();

if (length < required_pad)
  myString.insert(0, required_pad - length, ' ');

Come su:

string s = "          "; // 10 spaces
string n = "123";
n.length() <= 10 ? s.replace(10 - n.length(), n.length(), s) : s = n;

che stavo cercando l'argomento perché Im sviluppo VCL; Comunque facendo una funzione non era non è così difficile.

void addWhiteSpcs(string &str, int maxLength) {
    int i, length;

    length = str.length();
    for(i=length; i<maxLength; i++)
    str += " ";
};

string name1 = "johnny";
string name2 = "cash";

addWhiteSpcs(name1, 10);
addWhiteSpcs(name2, 10);

In entrambi i casi si aggiungerà alla destra 10 spazi vuoti. Raccomando di usare i font a spaziatura fissa come corriere o Consolas per un formato corretto.

Questo è ciò che accade quando non si sta usando monospazio carattere
johnny____
contanti ______

// using monospace font the output will be
johnny____
cash______

In entrambi i casi hanno la stessa lunghezza.

Create una nuova stringa di 10 spazi, e lavorare a ritroso in entrambe le stringhe.

string padstring(const string &source, size_t totalLength, char padChar)
{
    if (source.length() >= totalLength) 
        return source;

    string padded(totalLength, padChar);
    string::const_reverse_iterator iSource = source.rbegin();
    string::reverse_iterator iPadded = padded.rbegin();
    for (;iSource != source.rend(); ++iSource, ++iPadded)
        *iPadded = *iSource;
    return padded;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top