gpt4 book ai didi

javascript - 通过添加break\n来重新格式化JavaScript中的字符串?

转载 作者:行者123 更新时间:2023-11-28 20:39:26 25 4
gpt4 key购买 nike

我正在尝试在 javascript 中创建一个函数,该函数将接受一串文本作为参数,然后通过将 \n 添加到该字符串来格式化它,这将形成段落。

  • 每个段落的长度只能是 32 个字符
  • 在转到下一段时,我必须确保单词不会被切成两半”

示例字符串:

"If we listened to our intellect, we'd never have a love affair. We'd never have a friendship. We'd never go into business, because we'd be cynical. Well, that's nonsense. You've got to jump off cliffs all the time and build your wings on the way down."

之后的格式应该是这样的:

If we listened to our intellect, \n
we'd never have a love affair. \n
We'd never have a friendship.\n
We'd never go into business, \n
because we'd be cynical. Well, \n
that's nonsense. You've got to \n
jump off cliffs all the time and \n
build your wings on the way down"

我不确定如何解决这个问题,我不期望任何人解决整个解决方案,我只是想要一个起点,我在如何处理空格和单词以及何时插入\n 到字符串中。

最佳答案

这里有一个适合您的算法:

take your string; chop it up in two pieces: left (first 32 chars), right (the rest)
while right != empty
if length(left) == 32
while last character of left != space
take last char off of left, prepend it to right

print left
new left = first 32 chars of right; right = rest
end while

关于javascript - 通过添加break\n来重新格式化JavaScript中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14689081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com