私は使用std::string
していて、指定された幅にそれらを左パッドする必要があります。C ++でこれを行うための推奨される方法は何ですか?
サンプル入力:
123
10文字にパディングします。
サンプル出力:
123
(123の前に7つのスペース)
std::setw (setwidth) マニピュレータ
std::cout << std::setw (10) << 77 << std::endl;
また
std::cout << std::setw (10) << "hi!" << std::endl;
パディングされた 77 と "hi!" を出力します。
結果が文字列として必要な場合は、std::cout オブジェクトの代わりに std::stringstream のインスタンスを使用します。
ps: 担当ヘッダー ファイル<iomanip>
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;
}
次のように使用できます。
std::string s = "123";
s.insert(s.begin(), paddedLength - s.size(), ' ');
私が考えることができる最も簡単な方法は、stringstream を使用することです。
string foo = "foo";
stringstream ss;
ss << setw(10) << foo;
foo = ss.str();
foo
パディングする必要があります。
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;
}
を呼び出すことで、N 個のスペースを含む文字列を作成できます。
string(N, ' ');
したがって、次のようにすることができます。
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; }
素敵で簡単な方法があります:)
const int required_pad = 10;
std::string myString = "123";
size_t length = myString.length();
if (length < required_pad)
myString.insert(0, required_pad - length, ' ');
最小限の作業コード:
#include <iostream>
#include <iomanip>
int main()
{
for(int i = 0; i < 300; i += 11)
{
std::cout << std::setfill ( ' ' ) << std::setw (2) << (i % 100) << std::endl;
}
return 0;
}
/*
Note:
- for std::setfill ( ' ' ):
- item in '' is what will be used for filling
- std::cout may be replaced with a std::stringstream if you need it
- modulus is used to cut the integer to an appropriate length, for strings use substring
- std::setw is used to define the length of the needed string
*/
どうですか:
string s = " "; // 10 spaces
string n = "123";
n.length() <= 10 ? s.replace(10 - n.length(), n.length(), s) : s = n;
10スペースの新しい文字列を作成し、両方の文字列で逆方向に作業します。
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;
}