Javascript 如何计算字符串中两个字符之间的长度

Javascript 如何计算字符串中两个字符之间的长度,javascript,python,Javascript,Python,嘿,我试图创建一个函数,它接受一个字符串和一个字母作为参数,识别字符串中是否有两个字母,然后返回两个字母加上字母之间的字符数。 所以“星期六”和“a”将返回6 def sublength(string, char): new_string = '' for i in string: if i == char: new_string.append(i) if i != char: new

嘿,我试图创建一个函数,它接受一个字符串和一个字母作为参数,识别字符串中是否有两个字母,然后返回两个字母加上字母之间的字符数。 所以“星期六”和“a”将返回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)
            
我要做的是迭代字符串直到找到char,将这个字符添加到新的_字符串,继续迭代并添加后续字符,直到再次找到char,添加它,然后停止。这将在一次迭代中完成。但是,在当前构造时,我的函数会遍历所有字符串以查找匹配项,然后停止。 我如何在一次迭代中实现这一点,或者分解字符串以实现相同的功能? 谢谢

如果您也能提供JS解决方案,我将不胜感激

您可以使用string.index()方法缓解您的情况:

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()将返回字符在字符串中的位置。您可以使用它来查找索引以及它们之间的字符数

这是怎么回事?
  • 开始查找字符的第一个匹配项
  • end查找索引后第一个出现的字符 发现开始(这就是为什么从
    start+1
    索引以便搜索 从第一次发生到结束的字符串。因为 我们需要在其中搜索第二个事件(NECE)
  • 如果找到了两个索引,它将转到
    else
    返回差值 加2,因为它同时计算两个元素(仅差返回它们之间的字符数,不包括两者)
  • 如果两者都找不到,则返回字符串:
    “没有两个实例”
  • p.S.为
    sublength('Saturday','a')
    返回6,即按预期工作,一次性完成

    快捷方式:

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


    鲜为人知的事实是,
    str.index
    接受从何处开始搜索的第二个参数:

    >>> s = "Saturday"
    >>> first = s.index("a")
    >>> second = s.index("a", first + 1)
    >>> second - first + 1
    6
    
    这比
    string[start+1:][.index(char)
    更有效,因为这样做

    将其放入函数:

    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
    

    返回
    0
    如果
    char
    string

    中不存在两次,请构造一个包含字符串字符的数组,并使用数组。iloc

    我将使用正则表达式解决此问题。但是为了跟随你的尝试,当你在你的尝试旁边看到一个解决方案时,看看哪里出了问题

    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)
    
    但请记住,并没有检查大小写

    更新:这里是使用Regex的解决方案

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

    出于好奇,使用
    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
    
    一些测试:

    # 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
    


    您想要第一个重复的字母还是最大的重复间隔?您可以保留第一个和第二个字符“c”的索引。当前,当您追加时,您正在重新创建字符串。按设计字符串是不可变的。因此,最好通过索引对它们进行一次切片。我希望字符计数介于和包括两个常用字符之间。所以在我的“星期六”和“a”的例子中,答案是6:a-1,t-2,u-3,r-4,d-5,a-6。我希望在没有正则表达式的情况下执行此操作。我只对包含两次字符的字符串感兴趣,因此“banana”和“a”应返回0没有字符的任何字符串*2应返回0 ool!但是,如果字符串中没有目标字符,它将失败。无论如何,修改这个快捷方式来处理它很容易+这是回报。如何将其更改为按预期返回6?谢谢是 啊需要处理失败案例(不匹配、一个匹配、错误输入)输出以添加失败案例。这太棒了!你能解释一下end变量和return语句吗?谢谢<代码>索引处于起始位置。无需切割目标线,现在已修复!无需再次添加start,因为它合并了
    索引
    占据起始位置的结尾逻辑,这正是不需要对字符串进行切片的原因。让它在第一场比赛第二次看1分。(见@wim的答案…没有切片…没有问题)是的。若要添加它,将接受第三个参数作为结束索引,直到搜索到哪里。另外,将其包装在一个try-catch下,以避免边缘大小写错误。嗯……实际上我可能同意您的第二点。事实上,我更喜欢它,而不是额外遍历字符串来检查两个字符。但是很好。关于第一点,这是答案的质量问题。例如,有些人很难复制/粘贴你的答案来尝试或使用它你的第二个版本很好。得到我的投票。@Steve很不幸,必须检查2个字符,OP说我只对包含两次字符的字符串感兴趣,所以“banana”和“a”应该返回0。啊!我没有看到最近的评论。很酷。你的第二个解决方案有点酷,尽管很遗憾你必须做两次匹配。如果你先储存火柴,然后再使用两次,你就可以避免这种情况。
    # 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')