【每日一题0610】 实现一个trim()函数,去除字符串首尾的空格(不能使用strip()方法)

题目:实现一个trim()函数,去除字符串首尾的空格(不能使用strip()方法)
例:
1.字符串为空的情况,输入trim(’ ‘) 预期返回结果 ‘’
2.字符串首尾空格数大于1的情况,输入trim(’ a bc ') 预期返回结果 ‘a bc’

3 Likes

正则解法如下:

import  re
def trim(s):
   return re.sub(r'^(\s+)|(\s+)$', '',s)

正则解释:
^(\s+) 表示匹配以空格开头的字符串
(\s+)$ 表示匹配以空格结尾的字符串
| 表示或的意思

附录:
image

解法1:分别找到首位非空格的元素的下标,然后切片

def trim1(string):
    cursor_l = 0
    cursor_r = 0
    for i in range(len(string)):
        if string[i] != ' ':
            cursor_l = i
            print(cursor_l)
            break
    for i in range(len(string)):
        if string[::-1][i] != ' ':
            cursor_r = len(string)-i
            break
    return string[cursor_l:cursor_r]

思路2:先替换所有空格得到子串,再去原字符串中定位找字串首位元素的切片

def trim2(string):
    sub = string.replace(' ', '')
    return string[string.find(sub[0]):string.rfind(sub[-1]) + 1]
def trim(super):
    a = 0
    b = 0
    for i in range(len(super)):
        if super[i] == ' ':
            a += 1
        else:
            break
    for i in range(len(super)):
        if super[-(i+1)] == ' ':
            b += 1
        else:
            break
    print(a,b)
    print(super[a:-b])

trim('        23 2    1231  123  ')
def trim(str_):
    start = 0
    while start + 1 < len(str_) and str_[start] == " ":
        start += 1
    end = len(str_)
    while end > start and str_[end-1] == " ":
        end -= 1
    return str_[start:end]


test1 = "  ab c  "
test2 = "  ab"
test3 = "ab  "
test4 = "    "
test5 = ""

assert trim(test1) == "ab c"
assert trim(test2) == "ab"
assert trim(test3) == "ab"
assert trim(test4) == ""
assert trim(test5) == ""

棒棒的!

棒棒的!相信跟你对接的研发肯定很幸福,用例很到位!

def trim(super):
    a = 0
    b = 0
    for i in range(len(super)):
        if super[i] == ' ':
            a += 1
        else:
            break
    for i in range(len(super)):
        if super[-(i+1)] == ' ':
            b += 1
        else:
            break
    if b==0:
        return super[a:]
    else:
        return super[a:-b]

assert trim('abc') == 'abc'
assert trim('a b c') == 'a b c'
assert trim(' abc ') == 'abc'
assert trim('  abc') == 'abc'
assert trim('abc  ') == 'abc'
assert trim('  abc  ') == 'abc'
assert trim('  a  b  c  ') == 'a  b  c'
def trim(str):
    head = 0
    tail = len(str) - 1
    for i in range(len(str)):
        if str[i] == " ":
            head += 1
        else:
            break
    for i in range(len(str)-1, 0, -1) and str[i] == " ":
        if str[i] == " ":
            tail -= 1
        else:
            break
    return str[head: tail+1]

assert trim('abc') == 'abc'
assert trim('a b c') == 'a b c'
assert trim(' abc ') == 'abc'
assert trim('  abc') == 'abc'
assert trim('abc  ') == 'abc'
assert trim('  abc  ') == 'abc'

image
只适用于前后最多只有一个空格符号

关闭