首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

仅删除字符串中最后一次出现的单词

删除字符串中最后一次出现的单词可以通过以下步骤实现:

  1. 首先,将给定的字符串按照空格进行分割,得到一个单词列表。
  2. 然后,从列表的最后一个单词开始向前遍历,找到第一个与目标单词相同的单词。
  3. 一旦找到目标单词,将其从列表中删除。
  4. 最后,将剩余的单词重新连接成一个字符串。

以下是一个示例的Python代码实现:

代码语言:txt
复制
def delete_last_occurrence_of_word(sentence, target_word):
    words = sentence.split()
    for i in range(len(words)-1, -1, -1):
        if words[i] == target_word:
            del words[i]
            break
    return ' '.join(words)

# 示例用法
sentence = "This is a sample sentence. This is the last occurrence of the word sample."
target_word = "sample"
result = delete_last_occurrence_of_word(sentence, target_word)
print(result)

输出结果为:"This is a sample sentence. This is the last occurrence of the word."

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的结果

领券