在我的程序中,我可以接收各种长度的字符串并将它们发送以进行翻译。如果这些字符串具有特定的字符长度,则会出现错误,因此我想在出错之前检查和分割这些字符串。但是,我不能只是在单词中间分割字符串,还需要考虑单词本身的完整性。例如:
let str = "this is an input example of one sentence that contains a bit of words and must be split"
let splitStringArr = [];
// If string is larger than X (for testing make it 20) characters
if(str.length > 20) {
// Split string sentence into smaller strings, keep words intact
//...
// example of result would be
// splitStringArr = ['this is an input', 'example of one sentence' 'that contains...', '...']
// instead of ['this is an input exa' 'mple of one senten' 'ce that contains...']
}
但我不确定如何分割一句话并仍然考虑到句子长度。
解决此问题的方法是迭代字符串,将每个单词添加到其中,并每次检查它是否超过最大长度,否则开始一个新的数组索引,或者还有更好/现有的方法吗?
this is an input
而不是this is an input example
?如果你只想要少于maxLength
的单词,那么为什么'example of one sentence
的字符串长度大于20? - Code Maniac