Jakiś sposób na zastąpienie znaków w ciągu Swift?
Szukam sposobu na zastąpienie znaków w Swift String
.
Przykład: "This is my string"
Chciałbym zamienić with
+
na: "This+is+my+string"
.
Jak mogę to osiągnąć?
15 answers
Ta odpowiedź została zaktualizowana dla Swift 4 . Jeśli nadal używasz Swift 1, 2 lub 3, Zobacz historię wersji.
Masz kilka opcji. Możesz zrobić jak zasugerował @jaumard i użyćreplacingOccurrences()
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
I jak zauważył @cprcrack poniżej, parametry options
i range
są opcjonalne, więc jeśli nie chcesz określać opcji porównywania łańcuchów lub zakresu do wymiany, potrzebujesz tylko następujących elementów.
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")
Lub, jeśli dane są w określonym formacie w ten sposób, gdy zastępujesz znaki separacji, możesz użyć components()
, aby podzielić łańcuch na AND array, a następnie możesz użyć funkcji join()
, aby umieścić je z powrotem razem z określonym separatorem.
let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")
Lub jeśli szukasz szybszego rozwiązania, które nie wykorzystuje API z NSString, możesz użyć tego.
let aString = "Some search text"
let replaced = String(aString.map {
$0 == " " ? "+" : $0
})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-25 02:01:10
Możesz użyć tego:
let s = "This is my string"
let modified = s.replace(" ", withString:"+")
Jeśli dodasz tę metodę rozszerzenia w dowolnym miejscu w kodzie:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
}
Swift 3:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-27 12:50:31
Swift 3, Swift 4 Solution
let exampleString = "Example string"
//Solution suggested above in Swift 3.0
let stringToArray = exampleString.components(separatedBy: " ")
let stringFromArray = stringToArray.joined(separator: "+")
//Swiftiest solution
let swiftyString = exampleString.replacingOccurrences(of: " ", with: "+")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-15 18:00:06
Czy testowałeś to:
var test = "This is my string"
let replaced = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-13 08:51:10
Swift 4:
let abc = "Hello world"
let result = abc.replacingOccurrences(of: " ", with: "_",
options: NSString.CompareOptions.literal, range:nil)
print(result :\(result))
Wyjście:
result : Hello_world
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-10 06:06:22
Szybkie rozwiązanie 3 wzdłuż linii Sunkasa:
extension String {
mutating func replace(_ originalString:String, with newString:String) {
self = self.replacingOccurrences(of: originalString, with: newString)
}
}
Użycie:
var string = "foo!"
string.replace("!", with: "?")
print(string)
Wyjście:
foo?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-23 22:38:46
Używam tego rozszerzenia:
extension String {
func replaceCharacters(characters: String, toSeparator: String) -> String {
let characterSet = NSCharacterSet(charactersInString: characters)
let components = self.componentsSeparatedByCharactersInSet(characterSet)
let result = components.joinWithSeparator("")
return result
}
func wipeCharacters(characters: String) -> String {
return self.replaceCharacters(characters, toSeparator: "")
}
}
Użycie:
let token = "<34353 43434>"
token.replaceCharacters("< >", toString:"+")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-14 08:30:47
Kategoria modyfikująca istniejący zmienny ciąg znaków:
extension String
{
mutating func replace(originalString:String, withString newString:String)
{
let replacedString = self.stringByReplacingOccurrencesOfString(originalString, withString: newString, options: nil, range: nil)
self = replacedString
}
}
Użycie:
name.replace(" ", withString: "+")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-14 08:37:17
Swift 3 rozwiązanie oparte na odpowiedź Ramisa :
extension String {
func withReplacedCharacters(_ characters: String, by separator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
return components(separatedBy: characterSet).joined(separator: separator)
}
}
Próbowałem wymyślić odpowiednią nazwę funkcji zgodnie z Konwencją Swift 3 nazewnictwa.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:41
Oto przykład dla Swift 3:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-20 07:57:43
Oto rozszerzenie dla metody in-place occurrences replace na String
, która nie ma niepotrzebnej kopii i robi wszystko na swoim miejscu:
extension String {
mutating func replaceOccurrences(of target: String, with replacement: String, options: String.CompareOptions = [], locale: Locale? = nil) {
var range: Range<String.Index>?
repeat {
range = self.range(of: source, options: options, range: range.map { $0.lowerBound..<self.endIndex }, locale: locale)
if let range = range {
self.replaceSubrange(range, with: new)
}
} while range != nil
}
}
(podpis metody naśladuje również podpis wbudowanej metody String.replacingOccurrences()
)
Może być użyty w następujący sposób:
var string = "this is a string"
string.replaceOccurrences(of: " ", with: "_")
print(string) // "this_is_a_string"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-05 12:50:51
Jeśli nie chcesz używać metod Objective-C NSString
, możesz po prostu użyć split
i join
:
var string = "This is my string"
string = join("+", split(string, isSeparator: { $0 == " " }))
split(string, isSeparator: { $0 == " " })
zwraca tablicę łańcuchów (["This", "is", "my", "string"]
).
join
łączy te elementy z +
, dając pożądany wynik: "This+is+my+string"
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-18 14:00:02
Zaimplementowałem ten bardzo prosty func:
func convap (text : String) -> String {
return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}
Więc możesz napisać:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-18 09:16:04
Myślę, że Regex jest najbardziej elastyczny i solidny sposób:
var str = "This is my string"
let regex = try! NSRegularExpression(pattern: " ", options: [])
let output = regex.stringByReplacingMatchesInString(
str,
options: [],
range: NSRange(location: 0, length: str.characters.count),
withTemplate: "+"
)
// output: "This+is+my+string"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-31 03:29:44
Rozszerzenie Swift:
extension String {
func stringByReplacing(replaceStrings set: [String], with: String) -> String {
var stringObject = self
for string in set {
stringObject = self.stringByReplacingOccurrencesOfString(string, withString: with)
}
return stringObject
}
}
Go on and use it like let replacedString = yorString.stringByReplacing(replaceStrings: [" ","?","."], with: "+")
Prędkość funkcji jest czymś, z czego nie mogę być dumny, ale możesz przekazać tablicę String
W Jednym przejściu, aby wykonać więcej niż jedną zamianę.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-03 22:42:05