# How to count the length between two characters in a string

## Question:

Hey I’m trying to create a function that takes in a string and a letter as arguments, identifies if there are two of this letter within the string, and then returns the number of characters between the two plus the letters.
So ‘Saturday’ and ‘a’ would return 6.

``````def sublength(string, char):
new_string = ''
for i in string:
if i == char:
new_string.append(i)
if i != char:
new_string.append(i)
if i == char:
new_string.append(i)
break
return len(new_string)

``````

What I want to do is iterate through string until char is found, add this character to new_string, continue to iterate and add the subsequent characters until char is found again, add it and then stop. This would be done in one iteration. However, as it’s currently constructed, my function iterates through all of the string looking for matches and then stops.
How do I either do this in one iteration or break up the string to achieve the same functionality?
Thanks!

If you can provide a solution in JS as well I would really appreciate it!!

You can use string.index() method to ease your situation:

``````def sublength(string, char):
try:
start = string.index(char)
end = string.index(char, start+1)
except: return 'No two instances'
else: return end +2
``````

index() will return the position of character in the string. You can use it to find indices and number of characters between them.

## How does this works?

1. start finds first occurrence of character
2. end finds first occurance of character AFTER the index at which
start is discovered (thats why indexing from `start+1` so to search
string from after the first occurance till end. Because thats
where we need to search for second occurenece)
3. if both indices are found, it goes on to `else` to return difference
Plus 2 as it is counting both elements (mere difference return number of characters between them excluding both)
4. if both arent found it returns string : `'No two instances'`

P.S. returns 6 for `sublength('Saturday', 'a')` i.e. works as intended and is one-go!

Shortcut method:

``````try:
print(string[string.index(char)+1:].index(char)+2)
except:
print(char ,'is not present twice in ', string)
``````

OR

``````pos = string[string.find(char)+1:].find(char)+2
if pos == 1 :
print(char ,'is not present twice in ', string)
else:
print("Are present at a distance of",pos)
``````

Little known fact, `str.index` accepts a second argument for where to begin searching from:

``````>>> s = "Saturday"
>>> first = s.index("a")
>>> second = s.index("a", first + 1)
>>> second - first + 1
6
``````

This is more efficient than `string[start+1:].index(char)` because that way makes an unnecessary copy.

Putting it into a function:

``````def sublength(string, char):
if string.count(char) != 2:
return 0
first = string.index(char)
second = string.index(char, first + 1)
return second - first + 1
``````

Returns `0` if `char` is not present exactly twice within `string`.

I would solve this by using regex. But to follow your try, see whats wrong when you see a solution next to your try.

``````def sublength(string, char):
new_string = ''
found = False
for i in string:
if i == char:
new_string += i
found = True
else:
new_string += i
found = False
break
elif found:
new_string += i
if found:
new_string = ""
return len(new_string)
``````

But keep in mind, there is no check for upper and lower case …

Update: Here the solution with Regex

``````import re
if re.search("a.*?a", "Saturday"):
print(len(re.search("a.*?a", "Saturday").group(0)))
else:
print("Nope")
``````

Just out of curiosity, an approach using `regex`:

``````import re

def substring_length(string, char):
match = re.search(f'{char}.+{char}', string)
match_length = len(match.group(0)) if match else 0
return match_length
``````

Some tests:

``````# Returns the expected results when there are two target characters
print(substring_length('Saturday', 'a'))
6

# Returns 0 when there aren't at least two target characters
print(substring_length('Saturday', 'z'))
0

# When there are more than two target characters, calculate the length from the start matching character to the last matching character
print(substring_length('Researcher', 'e'))
8
``````
``````def f(s, c):
s = s.lower()
if s.count(c) != 2:
return 0
return s.index(c, mn+1)-s.index(c)+1

f('Saturday', 'a')
``````

Little long solution:-

``````public static int getCharBetween(String s, char c){
if(s.equals(null) ||s.length()==0){
return -1;
}
char[] ch=s.toCharArray();
List<Integer> list= new ArrayList<>();
for(char cha:ch){
if(cha==c){
s=s.substring(s.indexOf(cha)+1, s.length()-1);
if(list.size()==2){
break;
}
}
}
if(list.size()==0){
return -1;
}
return (list.get(1)-list.get(0))-1;
}
``````

In JavaScript, you could do it this way:

``````function subLength(word, character) {
const regexString = `[\${character}]`;
const regex = new RegExp(regexString, 'g');
const found = word.match(regex);

if (found.length !== 2) {
return 0;
}

first = word.indexOf(character);
second = word.lastIndexOf(character);

return second - first + 1;
};

subLength('Saturday', 'a'); // returns 6
``````
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.