OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to count the length between two characters in a string

  • Thread starter Thread starter Wiseface
  • Start date Start date
W

Wiseface

Guest
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.

Code:
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!!

<p>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.</p>
<pre><code>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)

</code></pre>
<p>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!</p>
<p><strong>If you can provide a solution in JS as well I would really appreciate it!!</strong></p>
 

Latest posts

Z
Replies
0
Views
1
zuegelwagen
Z
Top