用python作答下題埋市,不可使用strip和re:給定一個(gè)字符串S姥宝,去除S首尾的空格,并將字符串中間連續(xù)的多個(gè)空格替換為1個(gè)空格恐疲,返回處理后的字符串腊满。
GPT4作答
def remove_extra_spaces(s):
# 初始化一個(gè)空列表來(lái)存儲(chǔ)單詞
words = []
# 初始化一個(gè)空字符串來(lái)存儲(chǔ)當(dāng)前的單詞
word = ''
# 遍歷字符串中的每個(gè)字符
for c in s:
# 如果當(dāng)前字符不是空格,將其添加到當(dāng)前單詞
if c != ' ':
word += c
# 如果當(dāng)前字符是空格培己,且當(dāng)前單詞不為空碳蛋,將當(dāng)前單詞添加到單詞列表,并清空當(dāng)前單詞
elif word:
words.append(word)
word = ''
# 如果最后一個(gè)單詞不為空省咨,將其添加到單詞列表
if word:
words.append(word)
# 使用單個(gè)空格連接單詞列表肃弟,得到處理后的字符串
return ' '.join(words)
# 測(cè)試
s = ' hello world '
result = remove_extra_spaces(s)
print(result) # 輸出:'hello world'
在這個(gè)函數(shù)中,我們首先初始化了一個(gè)空列表words來(lái)存儲(chǔ)單詞零蓉,以及一個(gè)空字符串word來(lái)存儲(chǔ)當(dāng)前的單詞笤受。然后,我們遍歷字符串中的每個(gè)字符敌蜂。如果當(dāng)前字符不是空格箩兽,我們將其添加到當(dāng)前單詞。如果當(dāng)前字符是空格章喉,且當(dāng)前單詞不為空汗贫,我們將當(dāng)前單詞添加到單詞列表,并清空當(dāng)前單詞秸脱。最后落包,我們使用單個(gè)空格連接單詞列表,得到處理后的字符串摊唇。
我的答案
def my_strip(s):
if not s:
return ''
start = 0
end = len(s) - 1
while start <= end and s[start] == ' ':
start += 1
while end >= start and s[end] == ' ':
end -= 1
return s[start:end+1]
def normilize(s):
s=my_strip(s)
if not s:
return ''
i=1
n=len(s)
res=''
while i<n-1:
if s[i]!=' ':
res+=s[i]
else:
if s[i+1]!=' ':
res+=' '
i+=1
return res