代码之家  ›  专栏  ›  技术社区  ›  nes1983

删除字符串最后一部分的优雅方法?

  •  7
  • nes1983  · 技术社区  · 14 年前

    在Smalltalk中,如果给定字符串'onetwother',我想删除最后的'Three'部分,例如,在Squeak method finder符号中: 'OneTwoThree' . 'Three' . 'OneTwo' .

    我能想到的最好办法是:

    'OneTwoThree' allButLast: 'Three' size ,

    但它并不觉得很小气,因为它使用的是子字符串长度,而不是子字符串本身。你会怎么编码?

    4 回复  |  直到 14 年前
        1
  •  8
  •   Lukas Renggli    14 年前
    'OneTwoThree' readStream upToAll: 'Three'
    
        2
  •  6
  •   Janko MivÅ¡ek    14 年前

    我通常使用#copyReplaceAll:with:方法,如果最后一个字符串没有在原始字符串的其他地方重复,当然:

    'OneTwoThree' copyReplaceAll: 'Three' with: ''
    
        3
  •  2
  •   akuhn    14 年前

    在Moose项目中,应该有一个方法 #removeSuffix: 删除给定后缀(如果存在)。

        4
  •  1
  •   Anon.    14 年前

    如果仅在删除最后一个事件之后才需要所有内容:

    |原切口lastEnd currentEnd修改|

    原文:='一二三'。
    裁切:='三'。
    最后结束:=0。

    lastEnd:=原始索引of:cutOut startingAt:lastEnd+1。
    ]同时也是。

    ifFalse:[原件]