如何统计 Google 表格中某个单元格中出现多次的某个单词之前的字符数?

How to count the number of characters before a certain word appearing several times in a cell in Google Sheets?

我找到了下面的公式来计算某个单词前面的字符数,遵循此处提供的解决方案:

Count number of characters before a certain word in cell

=SEARCH("apple",A2)-1

我的问题如下:

如何计算同一单元格中两次出现的同一个词之间的中间字符?

改编 Nicole 的例子 here):

"I need to count the number of characters in a text string before a word. For example, lets say the word is "Apple"。文本字符串为 "I plucked an apple from that beautiful tree"。在这种情况下,字符数为 13。"

假设我的例子是:

"I plucked an apple, from the red apple tree".

=SEARCH("apple",A2)-1 公式 returns 直到单词“apple”第一次出现的字符数。也就是 13.

如何用脚本计算单词“apple”两次出现之间的字符数?

, from the red”的长度是多少?

或者是否可以通过修改公式来实现 =SEARCH("apple",A2)-1?

非常感谢您的帮助和指导!

搜索函数可以采用第三个参数,它是您要在字符串中开始搜索的位置,因此如果您找到 "apple" 的第一个实例,然后 运行 另一个搜索从该位置加 1,您将找到第二个实例。

一审:

=search("apple", A2)

二审:

=search("apple", A2, search("apple", A2) + 1)

从第一个减去第二个:

=search("apple", A2, search("apple", A2) + 1) - search("apple", A2)

要获得两者之间的长度,您必须减去单词 "apple" 或您要搜索的任何内容的长度。

=INDEX(LEN(SPLIT($A,"apple",0)))
  • SPLIT 正文 apple
  • 计算每个字符串的 LENgth
  • INDEX 获取数组中的相应索引

    =INDEX(LEN(SPLIT($A,"apple",0)),2)
    

var str = "I plucked an apple, from the red apple tree";
var len = str.split('apple', 2).map(e=>e.length);
console.info(len);
console.info(len[1]);

如果你想用脚本来做,你可以玩“indexOf”函数。它计算从字符串开头到您引入的单词有多少个字符。 indexOf 是这样工作的:

indexOf(string, [pos])

如果不指定任何位置,则从头开始计算,否则从您介绍的位置开始计算。 话虽如此,您可以应用以下逻辑:

var string = sheet.getRange("your cell").getValues().toString();

var apple_length = "apple".length;  
var first_apple = string.indexOf("apple") + apple_length;
var second_apple = string.indexOf("apple", first_apple);

var result = second_apple - first_apple;

因为它一直计数直到找到单词,所以我们需要将单词的长度添加到公式中,并将该结果用作第二个 indexOf 的起始位置。

有关详细信息,请查看 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

编辑

var appletree = [];
var apple_length = "apple".length;
var char_counter = 0;

while (true) {

var apple = your_string.indexOf("apple", char_counter) + apple_length;

appletree.push(apple);

char_counter = char_counter + apple;


if (char_counter >= your_string.length) 
 break;

};
};

这实际上更简单更好,因为它与字符串长度或放置多少苹果无关。

=FINDB("♥", SUBSTITUTE(A1, "apple", "♥"))-1