如何在Swift中获取字符串的一部分?

7

我想了解如何在Swift中获取字符串的一部分。我正在寻找Mid$,Right$和Left$函数的Swift等效函数。任何帮助都将不胜感激。


我不是 Swift 程序员,但您是否尝试查看这个答案?https://dev59.com/rWAg5IYBdhLWcg3wBXKs - Rawa
你有阅读过文档吗? - jtbandes
请打开以下网址:http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/,并滚动到“检索子字符串”一节。 - Nick Meyer
为什么这个被踩了?@Rawa提供的问题与此问题不同,它不是重复的。对于这个问题,非Stack Overflow答案不在Stack Overflow上,因此这是一个我们需要在这里回答的问题。 - Abhi Beckert
5个回答

9

Swift 4, Swift5

现代API采用以下语法:

let str = "Hello world!"
let prefix = String(str.prefix(1))
let suffix = String(str.suffix(1))

4

编辑:此回答发布于2014年,已经过时,我建议参考Vyacheslav的答案

Left的等效函数是substringToIndex

例如(直接引用这个网站的内容)

let myString = "ABCDEFGHI"
let mySubstring = (myString.substringToIndex(2))
//This grabs the first 2 digits of the string and stops there,
//which returns "AB"

Right的(大致)相当于substringFromIndex

例如:(直接引用自同一网站

let myString = "ABCDEFGHI"
let mySubstring = (myString.substringFromIndex(2))
//This jumps over the first 2 digits of the string and grabs the rest,
//which returns "CDEFGHI"

请查看https://web.archive.org/web/20170504165315/http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/,其中包含与Swift相关的字符串参考指南。

谢谢。我非常感激。在发布问题之前,我确实花了一个多小时寻找答案。 - jlert
由于Xcode 7.3.1的原因,此方法无法正常工作。在substringFromIndex方法中使用任何Int都会导致clang错误:String may not be indexed with 'Int', it has variable size elements. - johnnyclem

1
在Swift 4中,Left()和right()的等效函数是prefix()和suffix()。Mid()的等效函数缺失。我希望有一个名为infix(position:length)的函数来完成这个功能。

1
这是我基于 Aristocrates 的答案编写的 rightString、leftString 和 midString 函数版本。
var myString = "abcdefghijklmnopqrstuvwxyz987654321"

func leftString(theString: String, charToGet: Int) ->String{

var indexCount = 0
let strLen = countElements(theString)

if charToGet > strLen { indexCount = strLen } else { indexCount = charToGet }
if charToGet < 0 { indexCount = 0 }

let index: String.Index = advance(theString.startIndex, indexCount)
let mySubstring:String = theString.substringToIndex(index)

return mySubstring
}

func rightString(theString: String, charToGet: Int) ->String{

var indexCount = 0
let strLen = countElements(theString)
var charToSkip = strLen - charToGet

if charToSkip > strLen { indexCount = strLen } else { indexCount = charToSkip }
if charToSkip < 0 { indexCount = 0 }

let index: String.Index = advance(theString.startIndex, indexCount)
let mySubstring:String = theString.substringFromIndex(index)

return mySubstring
}

func midString(theString: String, startPos: Int, charToGet: Int) ->String{

let strLen = countElements(theString)
var rightCharCount = strLen - startPos

var mySubstring = rightString(theString, rightCharCount)
 mySubstring = leftString(mySubstring, charToGet)

return mySubstring
}

var myLeftString = leftString(myString, 3)
// returns "abc"

var myRightString = rightString(myString, 5)
// returns "54321"

var myMidString = midString(myString, 3, 5)
// returns "defgh"

0

这里的解决方案似乎都已经过时了。以下是我在Swift 2.0中获取字符串左侧和右侧指定数量字符的方法:

public extension String
{


    public var length: Int { return self.characters.count }  // Swift 2.0


    public func substringToCharactersCount(count: Int) -> String?
    {
        // Discussion:  Equivalent to "left".  Gets the beginning portion of the string with the specified number of characters.  It is friendly to having a count that exceeds the length of the string, returning the portion that it can.

        // returnString
        var returnString: String?

        // length
        let length = self.length

        if length > 0
        {
            // useCount
            let useCount: Int

            if count > length
            {
                useCount = length
            }
            else
            {
                useCount = count
            }

            if useCount > 0
            {
                // useEndIndex
                let useEndIndex = self.startIndex.advancedBy(useCount)

                returnString = self.substringToIndex(useEndIndex)
            }
        }

        return returnString
    }



    public func substringFromCharactersCount(count: Int) -> String?
    {
        // Discussion:  Equivalent to "right".  Gets the ending portion of the string with the specified number of characters.  It is friendly to having a count that exceeds the length of the string, returning the portion that it can.

        // returnString
        var returnString: String?

        // length
        let length = self.length

        if length > 0
        {
            // useCount
            let useCount: Int

            if count > length
            {
                useCount = length
            }
            else
            {
                useCount = count
            }

            if useCount > 0
            {
                // useStartIndex
                let useStartIndex = self.startIndex.advancedBy(length - useCount)

                returnString = self.substringFromIndex(useStartIndex)
            }
        }

        return returnString
    }



}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接