比如说我有下面的话
THIS TEXT IS A SAMPLE TEXT
我的字符索引为 7。
然后,当我将句子拆分为单词时,我必须返回索引 1,该索引是包含字符索引的单词的索引,而不是 5,它与构成字符索引的单词完全匹配,但不是字符所在的正确索引。
基本上我试图返回字符所在位置的正确单词索引(当拆分为单词时)和字符索引(当与字符拆分时)
我想我会用下面的东西重建这个单词,以找到该字符处的单词
let curString = 'find a word from here';
let initialPositin = 5
let position = initialPositin
let stringBuilder = '';
while(position > -1 && curString.charAt(position) !== ' '){
console.log('run 1')
console.log(position);
stringBuilder = curString.charAt(position) + stringBuilder;
position --;
}
console.log(stringBuilder)
position = initialPositin + 1;
while(position < curString.length && curString.charAt(position) !== ' '){
console.log('run 2')
stringBuilder += curString.charAt(position);
position ++;
}
console.log(stringBuilder);
然后将句子拆分成单词,然后找到包含我构建的单词的所有单词索引。然后遍历所有找到的单词并重建之前的单词,看看重建中目标字符的索引是否与给定的字符位置匹配。
感觉效率并不高。大家有更好的建议吗
我更喜欢 javascript,但我可以尝试自己翻译任何其他语言
我认为你可以只计算给定索引之前出现的空格,比如
let curString = 'find a word from here';
let givenIndex = 9;
let spaceIndex = 0;
for (var i = 0; i < curString.length; i++) {
if(curString.charAt(i) == ' ') {
if (i < givenIndex) {
spaceIndex++;
} else {
// found what we need
console.log(spaceIndex);
}
}
}
也许您可以构建一个返回所有空格位置的函数。 然后您可以看到字符索引在该空间位置列表中的位置。
text = "THIS TEXT IS A SAMPLE TEXT"
indexes = []
current_word = 0
for i in range(0, len(text)):
if text[i] == ' ':
current_word += 1 # After a ' ' character, we passed a word
else:
indexes.append(current_word) # current character belongs to current word
您可以使用这段代码(用Python3编写)构建一次索引数组,然后您可以将它用于每个索引。如果您还想计算索引数组中的 ' ' 字符,您可以简单地将它们添加到 for 循环中(在 if 语句中)。
我最终使用了下面的代码
let content = 'THIS IS A SAMPLE SENTENCE';
let target = 13;
let spaceCount = 0;
let index = 0;
while(index < target) {
if (content.charAt(index) === ' ') {
spaceCount++;
}
index++;
}
let splitContent = content.split(' ');
splitContent[spaceCount] = '#' + value
console.log(splitContent.join(' '))
工作得很好
就像 @miradham 的答案一样,该函数计算给定索引之前的空格,但使用内置函数来计算字符出现次数。
function wordIndexOfCharacterIndexInString(index, string) {
const stringUpToCharacter = string.slice(0, index)
return (stringUpToCharacter.match(/ /g) || []).length
}
console.log(wordIndexOfCharacterIndexInString(7, "THIS TEXT IS A SAMPLE TEXT"))
提出了一个扩展函数,根据特定字符索引返回单词索引
fun String.wordByCharIndex(index: Int): Int {
if (index !in 0..this.length || this[index].isWhitespace()) return ""
return(this.substring(0, index).count { it == ' ' })
}
或其更新版本直接返回该单词
fun String.wordByCharIndex(index: Int): String {
if (index !in 0..this.length || this[index].isWhitespace()) return ""
return(this.split(" ")[this.substring(0, index).count { it == ' ' }])
}
我已经针对多种情况对其进行了测试,并且它有效。不确定是否有更好的优化变体。