У меня есть длинная строка, и я хочу разбить эту длинную строку на 128 слов пары массивов. Например. строка содержит 500 слов. тогда окончательный вывод должен быть массивом из 3 элементов
элемент имеет первые 128 слов, второй элемент имеет следующие 128 слов, а третий элемент должен содержать остальные слова.
Я пробовал много способов, но не работал для меня. помогите пожалуйста если кто знает
заранее спасибо.
какова ваша попытка? Stack Overflow — не то место, где можно задавать проблемы с кодированием и ожидать ответов, когда вы не показали, что пробовали.
так что-то вроде разделения строки на куски? разделите строку на пустое место, а затем сделайте это stackoverflow.com/questions/8495687/split-array-into-chunks
Кроме того, либо ваш вопрос запутан, либо ваша арифметика отключена. Разве <500 words>
не следует разбивать на [<words 1 - 128>, <words 129 - 256>, <words 257 - 388>, and <words 289 - 500>]
, который состоит из четырех групп?
поэтому разделите его на слова и соедините 128, 128 и поместите остальные в последний массив....
Если вы хотите, чтобы каждый массив содержал 128 слов, а не символов, вы можете сначала разделить строку по пробелу, чтобы сохранить слова в массиве, а затем разбить его на фрагменты следующим образом:
const string = "hello world hello world hello world "
const words = string.split(" ")
function sliceIntoChunks(arr, chunkSize) {
const noEmptyStrsArr = arr.filter(item => item.length > 0)
const res = [];
for (let i = 0; i < noEmptyStrsArr.length; i += chunkSize) {
const chunk = noEmptyStrsArr.slice(i, i + chunkSize);
res.push(chunk);
}
return res;
}
console.info(sliceIntoChunks(words, 2))
спасибо, @jessica-98 за ваше решение. Я добавил еще несколько строк, если кто-то хочет 128 слов в виде строки, а не отдельных слов. тогда вы можете рассмотреть это решение.
const string = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum,\"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of "
const words = string.split(" ")
function sliceIntoChunks(arr, chunkSize) {
const noEmptyStrsArr = arr.filter(item => item.length > 0)
const res = [];
for (let i = 0; i < noEmptyStrsArr.length; i += chunkSize) {
const chunk = noEmptyStrsArr.slice(i, i + chunkSize);
res.push(chunk);
}
return res;
}
var res=sliceIntoChunks(words, 128)
var newArr=[]
for(let i=0;i<res.length;i++){
/* for(let j=0;j<res[i].length;j++){
newArr.push()
}*/
newArr.push(res[i].join(" "))
}
console.info(newArr)
Поскольку здесь уже есть рабочие ответы, я поделюсь своим рекурсивным подходом. Но в будущем, пожалуйста, поделитесь работой, которую вы сделали сами. Если вы не смогли ничего закодировать, поделитесь некоторыми своими мыслительными процессами.
Здесь мы строим это поверх повторно используемой функции, chunk
которая разбивает любой массив на куски одинакового размера, а также, возможно, меньший последний кусок. Наша функция chunkWords
разбивает строку по пробелу, а затем запускает chunk
результат.
const chunk = (n) => (xs) =>
xs .length <= n ? [xs] : [xs .slice (0, n), ... chunk (n) (xs .slice (n))]
const chunkWords = (n) => (s) =>
chunk (n) (s .split (/\s+/)) // .map (ss => ss .join (' '))
console .log (
chunkWords (3) ('Now is the time for all good men to come to the aid of their party')
)
Если вы хотите, чтобы результат был преобразован обратно в строки, просто раскомментируйте вызов .map
в chunkWords
. Это даст ["Now is the", "time for all", "good men to", "come to the", "aid of their", "party"]
.
«Я пробовал много способов» на самом деле не описывает ваши усилия. Поделитесь некоторыми подробностями, пожалуйста.