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
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')
Get the nth occurrence of a letter in a string (python)
Using a generator expression:
text = "abcd#abcd#a#"
gen = (i for i, l in enumerate(text) if l == "#")
next(gen) # skip as many as you need
4
next(gen) # get result
9
As a function:
def index_for_occurrence(text, token, occurrence):
gen = (i for i, l in enumerate(text) if l == token)
for _ in range(occurrence - 1):
next(gen)
return next(gen)
Result:
index_for_occurrence(text, "#", 2)
9
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)
Find Nth occurrence of a character in a string
public int GetNthIndex(string s, char t, int n)
{
int count = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == t)
{
count++;
if (count == n)
{
return i;
}
}
}
return -1;
}
That could be made a lot cleaner, and there are no checks on the input.
Finding the nth occurrence of a character in a string in javascript
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);
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 occurence of a substring in a string in java?
Here is a shot for fun ;)
public static int findNthIndexOf (String str, String needle, int occurence)
throws IndexOutOfBoundsException {
int index = -1;
Pattern p = Pattern.compile(needle, Pattern.MULTILINE);
Matcher m = p.matcher(str);
while(m.find()) {
if (--occurence == 0) {
index = m.start();
break;
}
}
if (index < 0) throw new IndexOutOfBoundsException();
return index;
}
Related Topics
Remove Duplicates Form an Array
Es6 Arrow Functions Not Working on the Prototype
Rails 4 Client Side Validation
Why Does "True" == True Show False in JavaScript
Finding Variable Type in JavaScript
How to Make Cross-Domain Ajax Calls to Google Maps API
Ruby on Rails 4 JavaScript Not Executed
Triggering Onclick Event Using Middle Click
Set Default Value of JavaScript Object Attributes
Ios: Authentication Using Xmlhttprequest - Handling 401 Response
Using Jquery Hover with HTML Image Map
Has Anyone Else Run into Problems Styling Twitter Typeahead's Searchbar
Detect If Hovering Over Element with Jquery
How to Get Objects Value If Its Name Contains Dots
JavaScript with Embedded Ruby: How to Safely Assign a Ruby Value to a JavaScript Variable
Format a Number as 2.5K If a Thousand or More, Otherwise 900