简体   繁体   中英

How to convert Swift Character to String?

I want to return the first letter of a String as a String instead of as a Character :

func firstLetter() -> String {
    return self.title[0]
}

However, with the above I get Character is not convertible to String . What's the right way to convert a Character to a String?

This answer suggests creating a subscript extension, but the declaration for String already has a subscript method:

subscript (i: String.Index) -> Character { get }

Is that answer outdated, or are these two different things?

为什么不使用字符串插值将字符转换为字符串?

return "\(firstChar)"

Just the first character? How about:

var str = "This is a test"
var result = str[str.startIndex..<str.startIndex.successor()] // "T": String

Returns a String (as you'd expect with a range subscript of a String) and works as long as there's at least one character.

This is a little shorter, and presumably might be a fraction faster, but to my mind doesn't read quite so clearly:

var result = str[str.startIndex...str.startIndex]

As of Swift 2.3/3.0+ you can do something like this:

func firstLetter() -> String {
    guard let firstChar = self.title.characters.first else {
        return ""  // If title is nil return empty string
    }
    return String(firstChar)
}

Or if you're OK with optional String:

func firstLetter() -> String? {
    guard let firstChar = self.title.characters.first else {
       return nil
    }
    return String(firstChar)
}

Update for Swift 4 , also think an extension is better

extension String{
func firstLetter() -> String {
    guard let firstChar = self.first else {
        return ""
    }
    return String(firstChar)
}

I did some researches for the same type of question, and I found this way to get any character from any string:

func charAsString(str:String, index:Int) -> String {
    return String(Array(str)[index])
}

and for the first character you call

var firstCharAsString = firstLetter("yourString",0)

I am a not very good at programming yet but I think that this will do what you want

EDIT:

Simplified for your need:

func firstChar(str:String) -> String {
    return String(Array(str)[0])
}

I hope that it's what you need

let str = "My String"
let firstChar = String(str.characters.first!)

I was trying to get single characters from a parsed String into a String. So I wanted B from helpAnswer in String format not CHARACTER format, so I could print out the individual characters in a text box. This works great. I don't know about the efficiency of it. But it works. SWIFT 3.0
Thanks for everyones help.....

var helpAnswer = "ABC"
var String1 = ""
var String2 = ""
var String3 = ""


 String1 = (String(helpAnswer[helpAnswer.index(helpAnswer.startIndex, offsetBy: 0)]))
 String2 = (String(helpAnswer[helpAnswer.index(helpAnswer.startIndex, offsetBy: 1)]))
 String3 = (String(helpAnswer[helpAnswer.index(helpAnswer.startIndex, offsetBy: 1)])

This is what I would do:

func firstLetter() -> String {
var x:String = self.title[0]
    return x
}

First: The answer you refer to is still relevant. It adds Integer based indices to String (eg using advance()). The builtin String subscript only supports BidirectionalIndices (think of them more like cursors, not as array-indices). This is likely because the Characters are not usually stored as such in the String structure, but as UTF-8 or UTF-16. Positional access to the characters then requires decoding (which is why - in addition to the extra copying - Array(string)[idx] is really expensive).

If you really just want the first char, you could do this:

extension String {
  var firstCharacterAsString : String {
    return self.startIndex == self.endIndex
      ? ""
      : String(self[self.startIndex])
  }
}

最简单的方法是return "\\(self.title[0])"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM