手动计算字符串的长度

时间:2017-06-17 15:01:22

标签: python string

我有一个家庭作业,要求不使用内置函数进行字符串长度计算。

我的想法是使用柜台:

s = 0
while name[s] != "":
    s += 1

但是我仍然坚持如何解决string index out of range错误......或者实际上是否存在其他方式?

5 个答案:

答案 0 :(得分:3)

你有两个简单的选择:

添加try/except子句:

s = 0
try:
    while(name[s]):
       s += 1
except IndexError:
    pass
print(s)

或使用迭代器:

s = 0
for _ in name:
    s += 1
print(s)

答案 1 :(得分:1)

试试这个,

counter = 0
st = 'ABCDEF'
for i in st:
    counter += 1

print('Length of String is : ', str(counter))

答案 2 :(得分:0)

因此,字符串基本上是一系列字符。例如:

'hello' = ['h', 'e', 'l', 'l', 'o']

因此,如果您只是遍历此数组并在每个循环中将1添加到length变量,那么您将得到长度:

string = "hello"
length = 0
for character in string:
  length = length + 1
print(length)

这样,您甚至不必担心处理异常:)

在线试用

https://repl.it/IptA/0

进一步阅读

Strings

Lists

答案 3 :(得分:0)

有一个替代#34;愚蠢"通过为每个字符添加一个来计数:

  1. 指数搜索找到字符串长度的范围。
  2. 二进制搜索将字符串长度向下引导,从上一步中找到的范围开始。
  3. 带测试部分的代码:

    def is_valid_index(s, i):
        '''Returns True, if i is a valid index of string s, and False otherwise.'''
        try:
            s[i]
            return True
        except IndexError:
            return False
    
    def string_length(s):
        '''Returns the length of string s without built-ins.'''
        # Test for empty string (needed for the invariant
        # of the following exponential search.)
        if not is_valid_index(s, 0):
            return 0
    
        # Exponential search with low as inclusive lower bound
        # and high as exclusive upper bound.
        # Invariant for the loop: low is a valid index.
        low = 0
        high = 1
        while True:
            if is_valid_index(s, high):
                low = high
                high *= 2
                continue
    
            break
    
        # Binary search inside the found range
        while True:
            if low + 1 == high:
                return high
    
            middle = (low + high) // 2
            if is_valid_index(s, middle):
                low = middle
            else:
                high = middle
    
    
    # Test section
    print(string_length('hello'))
    
    # Test the first thousand string lengths
    for i in range(1000):
        s = 'x' * i
        if len(s) != string_length(s):
            print('Error for {}: {}'.format(i, string_length(s)))
    
    # Test quite a large string
    s = 'x' * 1234567890
    print(string_length(s))
    

    结果:

    5
    1234567890
    

答案 4 :(得分:-1)

字符串具有属性__len__,该函数返回字符串的长度。因此,以下解决方案不使用内置函数,但计算是微不足道的(没有计算操作,因此,它可能不是作业的意图):

def get_string_length(s):
    return s.__len__()

测试:

print(get_string_length('hello'))

结果:

5
相关问题