0

我有一个简单的程序,可以插入或附加一些空格来对齐文本。

f()
{
    string word = “This word”;
    const string space = “ “;
    int space_num = 5; // this number can vary 
    for (int i = 0; i < space_num; i++)
        {
            word.insert(0, space);
        }   
    cout << word;
}

现在这可行,但我想知道是否有更有效的方法来做到这一点。不是在优化我的程序方面,而是在标准实践方面。

我可以想象两种可能的方法:

1 - 有没有办法创建一个由 20 个空格组成的字符串,并附加这些空格的一部分,而不是重复添加一个空格。

2 – 有没有办法用可变数量的空格创建字符串并附加它?

4

2 回答 2

5

Yes, both take a number of copies and a character:

word.insert(0, space_num, ' ');
word.append(space_num, ' ');

For aligning text, keep in mind you can use a string stream and the <iomanip> header, such as std::setw as well.

于 2013-05-14T03:29:08.823 回答
2

1 - Is there a way to create a string of say 20 spaces, and append a portion of those spaces rather than repeatedly adding a single space.

Yes, try this:

 string spaces(20, ' ');
 string portionOfSpaces = spaces.substr(0,10); //first 10 spaces
 string newString = portionOfSpaces + word;

Generally, you can use substr to get a portion of spaces and do operations with that substring.

2 – Is there a way to create string with a variable number of spaces and append that?

Yes, see string constructor:string (size_t n, char c); and string::append

于 2013-05-14T03:29:56.497 回答