假设我们声明了一个字符串。。。
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个字符的块中没有任何空格。