因此,在我的程序中,我可以接收各种长度的字符串并将它们发送出去以进行翻译。如果这些字符串具有一定的字符长度,我会收到错误,因此我想在此之前检查并拆分这些字符串(如果有必要)。但我不能只在单词中间分割字符串,单词本身也需要完整并考虑在内。
例如:
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...']
}
但我不知道如何拆分句子并仍然考虑句子长度。
解决这个问题的方法是迭代字符串,将每个单词添加到其中并每次检查它是否超过最大长度,否则启动一个新的数组索引,或者是否有更好/现有的方法?
最佳答案
这是一个使用 reduce
的示例.
const str = "this is an input example of one sentence that contains a bit of words and must be split";
// Split up the string and use `reduce`
// to iterate over it
const temp = str.split(' ').reduce((acc, c) => {
// Get the number of nested arrays
const currIndex = acc.length - 1;
// Join up the last array and get its length
const currLen = acc[currIndex].join(' ').length;
// If the length of that content and the new word
// in the iteration exceeds 20 chars push the new
// word to a new array
if (currLen + c.length > 20) {
acc.push([c]);
// otherwise add it to the existing array
} else {
acc[currIndex].push(c);
}
return acc;
}, [[]]);
// Join up all the nested arrays
const out = temp.map(arr => arr.join(' '));
console.log(out);
关于javascript - 根据最大字符长度拆分字符串,但要考虑单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58204155/