2014-11-22 12 views
5

Ho una descrizione String che contiene la mia frase. Voglio solo scrivere la prima lettera in maiuscolo. Ho provato cose diverse ma la maggior parte di esse mi ha dato eccezioni ed errori. Im usando Xcode 6.Capitalizzazione del primo carattere di frase (Swift)

Ecco quello che ho provato finora

let cap = [description.substringToIndex(advance(0,1))] as String 
    description = cap.uppercaseString + description.substringFromIndex(1) 

Mi dà: Tipo 'String.Index' non è conforme al protocollo 'IntegerLiteralConvertible'

ho provato

func capitalizedStringWithLocale(locale:0) -> String 

Ma non riesco proprio a capire come farlo funzionare. Qualche idea?

risposta

2
import Foundation 

// A lowercase string 
let description = "the quick brown fox jumps over the lazy dog." 

// The start index is the first letter 
let first = description.startIndex 

// The rest of the string goes from the position after the first letter 
// to the end. 
let rest = advance(first,1)..<description.endIndex 

// Glue these two ranges together, with the first uppercased, and you'll 
// get the result you want. Note that I'm using description[first...first] 
// to get the first letter because I want a String, not a Character, which 
// is what you'd get with description[first]. 
let capitalised = description[first...first].uppercaseString + description[rest] 

// Result: "The quick brown fox jumps over the lazy dog." 

Si consiglia di assicurarsi che ci sia almeno un carattere nella tua frase prima di iniziare, altrimenti si otterrà un errore di runtime cercando di far avanzare l'indice oltre la fine della stringa.

8

In Swift 2, si può fare String(text.characters.first!).capitalizedString + String(text.characters.dropFirst())

+0

Inoltre, se si vuole un vero e solo prima lettera maiuscola stringa come "John" o "Doe" e non "John" e "DOE", si possono fare le seguenti: 'stringa (text.characters .prima!). capitalizedString + String (text.characters.dropFirst()). minuscolo() ' – KingChintz

3

Un'altra possibilità a Swift 3 -

extension String { 
    func capitalizeFirst() -> String { 
     let firstIndex = self.index(startIndex, offsetBy: 1) 
     return self.substring(to: firstIndex).capitalized + self.substring(from: firstIndex).lowercased() 
    } 
} 

Modifica per Swift 4
Avvertenze dall'alto Swift 3 code-

'sottostringa (a :)' è obsoleto: utilizzare l'indice di divisione stringa con un 'pa rtial range upto 'operator.
'sottostringa (da :)' è obsoleto: si prega di utilizzare pedice di affettatura stringa con un operatore 'intervallo parziale da'.

Swift 4 soluzione -

extension String { 
    var capitalizedFirst: String { 
     guard !isEmpty else { 
      return self 
     } 

     let capitalizedFirstLetter = charAt(i: 0).uppercased() 
     let secondIndex    = index(after: startIndex) 
     let remainingString   = self[secondIndex..<endIndex] 

     let capitalizedString  = "\(capitalizedFirstLetter)\(remainingString)" 
     return capitalizedString 
    } 
} 
1

Ecco come farlo a Swift 4; nel caso in cui se aiuta nessuno:

extension String { 
    func captalizeFirstCharacter() -> String { 
     var result = self 

     let substr1 = String(self[startIndex]).uppercased() 
     result.replaceSubrange(...startIndex, with: substr1) 

     return result 
    } 
} 

Non sarà mutare l'originale String.

1
extension String { 
var capitalizedFirstLetter:String { 
    let string = self 
    return string.replacingCharacters(in: startIndex...startIndex, with: String(self[startIndex]).capitalized) 
} 

}

let newSentence = sentence.capitalizedFirstLetter 
0

Per uno o ogni parola nella stringa, è possibile utilizzare la proprietà .capitalized di stringa.

print("foo".capitalized) //prints: Foo 

print("foo foo foo".capitalized) //prints: Foo Foo Foo