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

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

4 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
只适用于前后最多只有一个空格符号

def trimB(s:str):
    L = list(s)
    countF,countB = 0,0

    for item in L:
        if item == ' ':
            countF += 1
        else:
            break

    L.reverse()
    for item in L:
        if item == ' ':
            countB += 1
        else:
            break

    return ''.join(list(s)[countF:len(L)-countB])
def trim(string):
    list0 = []
    list1 = []
    sep = ''
    for i in string:
        list0.append(i)
    for num in range(len(list0)):
        if list0[num] != ' ':
            list1.append(num)
    try:
        num1 = list1[0]
        num2 = list1[-1]
        if (num1, num2 == True) and num1 != num2:
            result = sep.join(string[num1])
            for k in range(int(list1[0]), int(list1[-1])):
                num1 += 1
                result = result + string[num1]
            print(result)
    except:
        print('')

trim('        ')
trim(' adfs 4546     sfsdfj       ')
    def trim(s:str) ->str:
        lis = list(s)
        start = 0
        end = 0
        for i in range(len(s)):
            if " " != lis[i]:
                start = i
                break
            else:
                continue
        lis.reverse()
        for i in range(len(s)):
            if " " != lis[i]:
                end = i
                break
        if end == 0:
            return s[start:]
        return s[start:-end]
关闭