【问题标题】:AppleScript: Index of substring in stringAppleScript:字符串中子字符串的索引
【发布时间】:2010-12-15 13:04:12
【问题描述】:

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


比如:

substrUpTo(theStr, subStr)

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

【问题讨论】:

    标签: string function methods applescript substring


    【解决方案1】:
    set s to "Today is my birthday"
    set AppleScript's text item delimiters to "my"
    text item 1 of s
    --> "Today is "
    

    【讨论】:

    • 可能应该注意的是,最好的做法是在此之后立即将文本项分隔符重置为空字符串,以避免以后出现任何可能的奇怪错误。
    • 最佳实践总是在使用文本项分隔符或列表到文本强制转换(隐式和显式)之前立即将 TID 设置为适当的值。这是确保您的代码不易出错(即防御性编程)的唯一方法。礼貌的做法是将现有的 TID 存储在一个临时变量中,然后在完成后恢复它们(即在您找到它的状态下的全局“文本项分隔符”属性)。明智的做法是在处理程序中执行此操作,以防调用处理程序的代码行随后立即执行涉及 TID 的操作。
    【解决方案2】:

    内置的offset 命令应该可以做到:

    set s to "Today is my birthday"
    log text 1 thru ((offset of "my" in s) - 1) of s
    --> "Today is "
    

    【讨论】:

      【解决方案3】:

      可能有点笨拙,但它可以完成工作......

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        • 2014-05-08
        • 2014-03-17
        • 2021-11-10
        • 1970-01-01
        相关资源
        最近更新 更多