c++ - Efficiently appending or inserting a variable number of spaces to a string -
i have simple programme inserts or appends number of spaces align text.
f() { string word = “this word”; const string space = “ “; int space_num = 5; // number can vary (int = 0; < space_num; i++) { word.insert(0, space); } cout << word; }
now works, wondering if there more efficient way this. not in terms of optimizing programme, more in standard practice.
i can imagine 2 potential methods:
1 - there way create string of 20 spaces, , append portion of spaces rather repeatedly adding single space.
2 – there way create string variable number of spaces , append that?
yes, both take number of copies , character:
word.insert(0, space_num, ' '); word.append(space_num, ' ');
for aligning text, keep in mind can use string stream , <iomanip>
header, such std::setw
well.
Comments
Post a Comment