繁体   English   中英

如何在多行字符串中找到字符位置(行,列)?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM