Javascript 在javascript中查找字符串中第n次出现的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12744995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:09:58  来源:igfitidea点击:

Finding the nth occurrence of a character in a string in javascript

javascript

提问by sathish kumar

I am working on a javascript code to find the nth occurrence of a character in a string. Using the indexOf()function we are able to get the first occurrence of the character. Now the challenge is to get the nth occurrence of the character. I was able to get the second third occurrence and so on using the code given below:

我正在编写一个 javascript 代码来查找字符串中第 n 次出现的字符。使用该indexOf()函数,我们可以获得该字符的第一次出现。现在的挑战是获得该字符的第 n 次出现。我能够使用下面给出的代码获得第二次第三次出现,依此类推:

function myFunction() {
  var str = "abcdefabcddesadfasddsfsd.";

  var n = str.indexOf("d");
  document.write("First occurence " +n );

  var n1 = str.indexOf("d",parseInt(n+1));
  document.write("Second occurence " +n1 );

  var n2 = str.indexOf("d",parseInt(n1+1));
  document.write("Third occurence " +n2 );

  var n3 = str.indexOf("d",parseInt(n2+1));
  document.write("Fourth occurence " +n3);

  // and so on ...
}

The result is given below

结果如下

First occurence 3 
Second occurence 9 
Third occurence 10 
Fourth occurence 14 
Fifth occurence 18 
Sixth occurence 19

I would like to generalize the script so that I am able to find the nth occurrence of the character as the above code requires us to repeat the script n times. Let me know if there is a better method or alternative to do the same. It would be nice if we just give the occurrence (at run time) to get the index of that character.

我想概括脚本,以便我能够找到第 n 次出现的字符,因为上面的代码要求我们重复脚本 n 次。让我知道是否有更好的方法或替代方法来做同样的事情。如果我们只给出出现次数(在运行时)来获取该字符的索引,那就太好了。

The following are some of my questions:

以下是我的一些问题:

  • How do we do it in JavaScript?
  • Does any framework provide any functionality to do the same implementation in an easier way or what are the alternate methods to implement the same in other frameworks /languages?
  • 我们如何在 JavaScript 中做到这一点?
  • 是否有任何框架提供任何功能以更简单的方式执行相同的实现,或者在其他框架/语言中实现相同的替代方法是什么?

采纳答案by Marten

function nth_occurrence (string, char, nth) {
    var first_index = string.indexOf(char);
    var length_up_to_first_index = first_index + 1;

    if (nth == 1) {
        return first_index;
    } else {
        var string_after_first_occurrence = string.slice(length_up_to_first_index);
        var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);

        if (next_occurrence === -1) {
            return -1;
        } else {
            return length_up_to_first_index + next_occurrence;  
        }
    }
}

// Returns 16. The index of the third 'c' character.
nth_occurrence('aaaaacabkhjecdddchjke', 'c', 3);
// Returns -1. There is no third 'c' character.
nth_occurrence('aaaaacabkhjecdddhjke', 'c', 3);

回答by Nelson

You can do it easily by implementing a function using charAt(), like this:

您可以通过使用 实现函数来轻松完成charAt(),如下所示:

function nth_ocurrence(str, needle, nth) {
  for (i=0;i<str.length;i++) {
    if (str.charAt(i) == needle) {
        if (!--nth) {
           return i;    
        }
    }
  }
  return false;
}

alert( nth_ocurrence('aaaaacabkhjecdddchjke', 'c', 3)  );//alerts 16

Thanks to CQQL for let me know what OP really wanted. I updated a bit my original function to achieve the new behaviour.

感谢 CQQL 让我知道 OP 真正想要什么。我更新了一点我原来的功能来实现新的行为。

回答by kennebec

indexOf takes a second argument, the character index in the string to begin the search.

indexOf 接受第二个参数,即开始搜索的字符串中的字符索引。

function nthChar(string, character, n){
    var count= 0, i=0;
    while(count<n && (i=string.indexOf(character,i)+1)){
        count++;
    }
    if(count== n) return i-1;
    return NaN;
}

var s= 'abcbbasdbgasdnnaabaasdert';

nthChar(s,'a',7);

回答by foomip

So a nice way to do this is to extend the string class like so:

所以一个很好的方法是像这样扩展字符串类:

(function() {
  String.prototype.nthOccurrenceIndex = function(charToMatch, occurrenceIndex) {
    var char, index, matches, _i, _len;
    matches = 0;
    index = 0;
    for (_i = 0, _len = this.length; _i < _len; _i++) {
      char = this[_i];
      if (char === charToMatch) {
        matches += 1;
        if (matches === occurrenceIndex) {
          return index;
        }
      }
      index += 1;
    }
    return -1;
  };

}).call(this);

The much more concise CoffeeScript version:

更简洁的 CoffeeScript 版本:

String.prototype.nthOccurrenceIndex = (charToMatch, occurrenceIndex)->
  matches = 0
  index = 0

  for char in @
    if char is charToMatch
      matches += 1

      return index if matches is occurrenceIndex

    index += 1

  -1

So now you can do stuff like:

所以现在你可以做这样的事情:

"abcabc".nthOccurrenceIndex('a', 1)
# -> 0

"abcabc".nthOccurrenceIndex('a', 2)
# -> 3

"abcabc".nthOccurrenceIndex('a', 3)
# -> -1

"abcabc".nthOccurrenceIndex('a', 1)
# -> 0

"abcabc".nthOccurrenceIndex('a', 2)
# -> 3

"abcabc".nthOccurrenceIndex('a', 3)
# -> -1

回答by Sharon Choe

function nthIndexOf(search, n) {
    var myArray = []; 
    for(var i = 0; i < myStr.length; i++) {
        if(myStr.slice(i, i + search.length) === search) {
            myArray.push(i);            
        }
    }   
    return myArray[n - 1];
}

回答by HymanRed

A maybe clearer function. Recursive and copy the mechanism of indexOf:

一个可能更清晰的功能。递归复制机制indexOf

  • Doesn't cause an error if an incorrectnumber for nth (ie <= 0). It will return -1like you can give a negative number (or greater than the length of the string) asfromIndexto indexOf.
  • Can take a fromIndexargument (the same than for indexOf: An integer representing the index at which to start the search; the default value is 0.)
  • 如果第 n 个数字不正确(即 <= 0),则不会导致错误。它将返回-1就像你可以给(除弦的长度或更大)负数作为fromIndexindexOf
  • 可以接受一个fromIndex参数(与 for 相同indexOf表示开始搜索的索引的整数;默认值为 0。

function indexOfNth (string, char, nth, fromIndex=0) {
  let indexChar = string.indexOf(char, fromIndex);
  if (indexChar === -1){
    return -1;
  } else if (nth === 1) {
    return indexChar;
  } else {
    return indexOfNth(string, char, nth-1, indexChar+1);
  }
}


let test = 'string for research purpose';
console.log('first s:', indexOfNth(test, 's', 1));
console.log('second s:', indexOfNth(test, 's', 2));
console.log('15th s:', indexOfNth(test, 's', 15));
console.log('first z:', indexOfNth(test, 'z', 1));
console.log('-1th s:', indexOfNth(test, 's', -1));
console.log('first s starting from index=1:', indexOfNth(test, 's', 1, 1));