代码之家  ›  专栏  ›  技术社区  ›  Alexsander Akers

AppleScript:字符串中子字符串的索引

  •  9
  • Alexsander Akers  · 技术社区  · 16 年前

    我想创建一个函数,该函数返回一个特定字符串的子字符串,从该字符串的开头到另一个特定字符串的开头,但不包括该字符串的开头。思想?


    比如:

    substrUpTo(theStr, subStr)
    

    所以如果我输入 substrUpTo("Today is my birthday", "my") ,它将返回第一个参数的子字符串,直到但不包括第二个参数的起始位置。(即,它将返回 "Today is " )

    3 回复  |  直到 16 年前
        1
  •  13
  •   has    16 年前
    set s to "Today is my birthday"
    set AppleScript's text item delimiters to "my"
    text item 1 of s
    --> "Today is "
    
        2
  •  7
  •   duozmo    12 年前

    内置的 offset

    set s to "Today is my birthday"
    log text 1 thru ((offset of "my" in s) - 1) of s
    --> "Today is "
    
        3
  •  0
  •   Kee Hinckley Philip Regan    7 年前

    也许有点笨拙,但它完成了任务。。。

    property kSourceText : "Today is my birthday"
    property kStopText : "my"
    
    set newSubstring to SubstringUpToString(kSourceText, kStopText)
    
    return newSubstring -- "Today is "
    
    on SubstringUpToString(theString, subString) -- (theString as string, subString as string) as string
    
        if theString does not contain subString then
            return theString
        end if
    
        set theReturnString to ""
    
        set stringCharacterCount to (get count of characters in theString)
        set substringCharacterCount to (get count of characters in subString)
        set lastCharacter to stringCharacterCount - substringCharacterCount
    
        repeat with thisChar from 1 to lastCharacter
            set startChar to thisChar
            set endChar to (thisChar + substringCharacterCount) - 1
            set currentSubstring to (get characters startChar thru endChar of theString) as string
            if currentSubstring is subString then
                return (get characters 1 thru (thisChar - 1) of theString) as string
            end if
        end repeat
    
        return theString
    end SubstringUpToString
    
    推荐文章