假设我们声明了一个字符串...
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 宽度之后有空格,我想包装文本。
有人可以为我提供代码或任何帮助来创建这样的东西。
假设我们声明了一个字符串...
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 宽度之后有空格,我想包装文本。
有人可以为我提供代码或任何帮助来创建这样的东西。
解决这个问题的一个基本思路是跟踪该段中第 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 个字符的块中没有任何空格的情况。