[英]How do i find character position (row, col) in multi-line string?
如何在多行字符串中找到當前字符的位置? 如果字符串中的每一行都是相同的長度,那就很容易了。 例如
const str = `hello
hello
hello`
const findPos = (str, ind) => {
const [cols] = str.split('\n');
return { row: ind / cols.length | 0, col: ind % cols.length };
};
findPos(str, 12) // { row: 2, col: 2 }
但是,如果每一行的長度不同,我該怎么做? 例如
const str = `hello
from
my
old
friend!`
findPos(str , 12) // { row: 3, col: 1 }
使用 while 循環遍歷拆分行,從要走的字符數中減去當前行的長度。 如果長度短於要走的字符數,則將要走的字符返回為col
,並將迭代的行數作為row
:
const findPos = (input, indexToFind) => { const lines = input.split('\n'); let charsToGo = indexToFind; let lineIndex = 0; while (lineIndex < lines.length) { const line = lines[lineIndex]; const char = line[charsToGo]; if (char) { return { row: lineIndex, col: charsToGo }; } charsToGo -= line.length; lineIndex++; } return 'None'; }; const str = `hello from my old friend!` console.log(findPos(str , 12)); // { row: 3, col: 1 }
請注意,這不會將換行符視為要迭代的字符,這似乎符合您的預期輸出。 有關為字符串中的所有字符生成位置的示例,請參見以下代碼段:
const findPos = (input, indexToFind) => { const lines = input.split('\n'); let charsToGo = indexToFind; let lineIndex = 0; while (lineIndex < lines.length) { const line = lines[lineIndex]; const char = line[charsToGo]; if (char) { return { row: lineIndex, col: charsToGo }; } charsToGo -= line.length; lineIndex++; } return 'None'; }; const str = `hello from my old friend!` const lenWithoutNewlines = str.length - str.match(/\n/g).length; for (let i = 0; i < lenWithoutNewlines; i++) { console.log(findPos(str , i)); }
當您的要求是找出每個字符的位置數組時
您無需創建函數即可逐個查找位置。
此外,在創建對象時,您可以保留占位符和字符以便快速搜索。
const str = `hello from my old friend!` function createPos(str) { let out = str.split('\n').map(e => [...e]); let place = 1; return out.map((arr, row) => arr.map((char, col) => ({ char, row, col, place: place++ }))).flat(); } function findPos(str, n) { return createPos(str).find(e => e.place === n) } console.log('all chars\n', createPos(str)); console.log('found char\n',findPos(str, 12))
我的建議:
const findPosition = (input, indexToFind) => {
const preChunk = input.substr(0, indexToFind);
const row = preChunk.split('\n').length - 1;
const lastIndexOfNewLine = input.lastIndexOf('\n', indexToFind);
const col = lastIndexOfNewLine > 0 ? indexToFind - lastIndexOfNewLine - 1 : indexToFind;
return {row, col};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.