Get the index of the nth occurrence in a string
You can use split
, slice
& join
to achieve your requirement.
Logic
First split
your string with char
then use slice
to join split values upto nth
occurrence. Then simply join with char
. It's length
will be your answer.
Check below.
function getIndex(str, char, n) { return str.split(char).slice(0, n).join(char).length;}
console.log(getIndex('https://www.example.example2.co.uk', '.', 2)) // returns 19console.log(getIndex('https://www.example.example2.co.uk', '.', 1)) // returns 11console.log(getIndex('https://www.example.example2.co.uk', '.', 3)) // returns 28
Get the index of the nth occurrence of a string?
That's basically what you need to do - or at least, it's the easiest solution. All you'd be "wasting" is the cost of n method invocations - you won't actually be checking any case twice, if you think about it. (IndexOf will return as soon as it finds the match, and you'll keep going from where it left off.)
Find the nth occurrence of substring in a string
Mark's iterative approach would be the usual way, I think.
Here's an alternative with string-splitting, which can often be useful for finding-related processes:
def findnth(haystack, needle, n):
parts= haystack.split(needle, n+1)
if len(parts)<=n+1:
return -1
return len(haystack)-len(parts[-1])-len(needle)
And here's a quick (and somewhat dirty, in that you have to choose some chaff that can't match the needle) one-liner:
'foo bar bar bar'.replace('bar', 'XXX', 1).find('bar')
How to get the nth occurrence in a string?
const string = "XYZ 123 ABC 456 ABC 789 ABC";
function getPosition(string, subString, index) { return string.split(subString, index).join(subString).length;}
console.log( getPosition(string, 'ABC', 2) // --> 16)
Get index of nth occurrence of char in a string
Using LINQ to find the index of the 5'th a
in the string aababaababa
:
var str = "aababaababa";
var ch = 'a';
var n = 5;
var result = str
.Select((c, i) => new { c, i })
.Where(x => x.c == ch)
.Skip(n - 1)
.FirstOrDefault();
return result != null ? result.i : -1;
How to get the nth occurrence of a set of substrings in a given string using Javascript?
You could try using Regular Expressions like this:
let testString="A <br> B <br/> C <br /> D <br/>";
//Array of substrings to be searched for
let testItems=['<br>','<br/>','<br />'];
//Construction of the regular expression from the given array
let regex=new RegExp(testItems.join("|"),"g");
//Getting all matches for the provided regex and reducing it to an array of indices only
let indices=[...testString.matchAll(regex)].map(match=>match.index);
console.log(indices);
In a string, how to find the index of the first character of the nth occurrence of a substring Python
Here's a pretty short way:
def index_of_nth_occurrence(longstring, substring, n):
return len(substring.join(longstring.split(substring)[:n]))
longstring = "stackoverflow_is_stackoverflow_not_stackoverflow_even_though_stackoverflow"
substring = "stackoverflow"
n = 2
print(index_of_nth_occurrence(longstring, substring, n)
# 17
The trick here is using str.split()
to find non-overlapping occurrences of the substring, then join back the first n
of them, and check how many characters that totals up to. The very next character after would be the first character of the n
th occurrence of the substring.
This may be less efficient than an iterative/manual approach, and will ignore overlapping matches, but it's quick and easy.
Index of nth Occurrence of the string
There is a find_nth
template function in Boost: http://www.boost.org/doc/libs/1_54_0/doc/html/boost/algorithm/find_nth.html
#include <iostream>
#include <boost/algorithm/string/find.hpp>
using namespace std;
using namespace boost;
int main() {
string a = "The rain in Spain falls mainly on the plain";
iterator_range<string::iterator> r = find_nth(a, "ain", 2);
cout << std::distance(a.begin(), r.begin()) << endl;
return 0;
}
Related Topics
Return Json, But It Includes Backward Slashes "\", Which I Don't Want
C# Check the Empty or Null Value in All Datatable Values
C# Best Way to Run a Function Every Second, Timer VS Thread
How to Cast a List into a Type Which Inherits from List<T>
Pass Array into ASP.NET Core Route Query String
How to Change Cell Background Color in Wpf Datagrid
How to Make Blazor Http Get Json Async Request
How to Pass Jquery Variable Value to C# MVC
Documentdb With Azure Functions
How to Remove Time Portion of Date in C# in Datetime Object Only
How to Call Another Controller Action from a Controller in MVC
How to Use Variable in Feature File
Restsharp Serializing Json Objects to Post Parameters
Restsharp Post Request - Body With X-Www-Form-Urlencoded Values
Drawing a Triangle With Rounded Corners
C# Double - Tostring() Formatting With Two Decimal Places But No Rounding