【问题标题】:Wrap String with For Loop or If Statement用 For 循环或 If 语句包装字符串
【发布时间】:2012-04-18 19:58:47
【问题描述】:

假设我们声明了一个字符串...

string paragraphy = "This is a really really long string containing a paragraph long content. I want to wrap this text by using a for loop to do so.";

使用这个字符串变量,如果文本宽度超过 60 并且在 60 宽度之后有空格,我想换行。

有人可以提供代码或帮助我创建类似的东西吗?

【问题讨论】:

  • “换行”是指将\n 插入适当的位置?
  • 是的。所以在宽度 60 和空格之后换行。
  • 这听起来像是一个典型的家庭作业问题,如果是,你应该这样标记它。
  • 您需要向我们展示您的尝试,以及您遇到的具体问题。

标签: c++ string if-statement for-loop


【解决方案1】:

解决这个问题的一个基本思路是跟踪该段中第 60 个字符之前的一段字符串中的最后一个空格。

由于这是作业,我会让你想出代码,但是这里有一些粗略的上述建议的伪代码:

- current_position = start of the string
- WHILE current_position NOT past the end of the string
   - LOOP 1...60 from the current_position (also don't go past the end of the string)
      - IF the character at current_position is a space, set the space_position to this position
   - Replace the character (the space) at the space_position with a newline
   - Set the current_position to the next character after the space_position

- If you're printing the string rather than inserting newline characters into it, you would print any remaining part of the string here.

您可能还需要考虑在 60 个字符的块中没有任何空格的情况。

【讨论】:

  • 谢谢!我将自己尝试并发布我想出的代码。
猜你喜欢
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多