'How to count the length between two characters in a string
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!!
Solution 1:[1]
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)
Solution 2:[2]
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:
if not found:
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")
Solution 3:[3]
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
Solution 4:[4]
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')
Solution 5:[5]
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?
- start finds first occurrence of character
- end finds first occurance of character AFTER the index at which
start is discovered (thats why indexing from
start+1so to search string from after the first occurance till end. Because thats where we need to search for second occurenece) - if both indices are found, it goes on to
elseto return difference Plus 2 as it is counting both elements (mere difference return number of characters between them excluding both) - 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!
Solution 6:[6]
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){
list.add(s.indexOf(cha));
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | CainĂ£ Max Couto-Silva |
| Solution 4 | Vinay Emmaadii |
| Solution 5 | |
| Solution 6 | Parikshit |
