7

I would like to find out how to get a part of a string in Swift. I am looking for the Swift equivalents of the Mid$, Right$, and Left$ functions. Any help would be appreciated.

Vakas
  • 6,291
  • 3
  • 35
  • 47
jlert
  • 123
  • 1
  • 1
  • 4
  • I'm not a swift programmer buy have you tried looking at this answer? http://stackoverflow.com/questions/24044851/how-do-you-use-string-substringwithrange-or-how-do-ranges-work-in-swift – Rawa Aug 13 '14 at 03:02
  • Have you read any of the documentation? – jtbandes Aug 13 '14 at 03:09
  • http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/ scroll down to "Retrieving a substring" – Nick Meyer Aug 13 '14 at 03:15
  • Why is this being down voted? The question @Rawa provided is different to this question, it's not a duplicate. Non-stack overflow answers to this question are not on stack overflow, so it's a question that we need to have answered here. – Abhi Beckert Aug 13 '14 at 06:20

5 Answers5

9

Swift 4, Swift5

Modern API has got this syntax:

let str = "Hello world!"
let prefix = String(str.prefix(1))
let suffix = String(str.suffix(1))
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
4

Edit: This answer was from 2014 and is obsolete today, I recommend referencing Vyacheslav's answer instead

The equivalent of Left is substringToIndex

Example: (directly from this site)

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

The (rough) equivalent of Right is substringFromIndex

Example: (directly from the same site)

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"

See https://web.archive.org/web/20170504165315/http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/

Nick Meyer
  • 1,771
  • 1
  • 17
  • 29
  • Thank you. I really appreciate it. I did spend more than an hour looking for the answer before I posted the question. – jlert Aug 13 '14 at 12:30
  • this doesn't work as of Xcode 7.3.1. Using any Int in the substringFromIndex method results in the clang error: String may not be indexed with 'Int', it has variable size elements. – johnnyclem Jun 02 '16 at 18:02
1

Here are my versions of rightString, leftString and midString functions based on Aristocrates answer.

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"
Vakas
  • 6,291
  • 3
  • 35
  • 47
jlert
  • 123
  • 1
  • 1
  • 4
1

In Swift 4 the equivalents to Left() and right() are prefix() and suffix(). The Mid() equivalent is missing. I would expect a function called something like infix(position:length).

mretondo
  • 187
  • 1
  • 9
0

The solutions here all seemed out of date. This is what I ended up with for getting the left and right sides of a string with a number of characters in 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
    }



}
John Bushnell
  • 1,851
  • 22
  • 29