String को Manipulate करना
In this page:
import Foundation
string.split(separator: " ")
string.replacingOccurrences(of: "target", with: "replacement")
string.trimmingCharacters(in: .whitespacesAndNewlines)
Splitting a String
.split(separator:) एक string को दिए गए separator character के आस-पास पीस में तोड़ता है, substrings का एक array return करते हुए।
उदाहरण: Splitting a String
// Declare a constant `sentence`, set to `"Swift is fun to learn"`
let sentence = "Swift is fun to learn"
// Declare a constant `words`, set to `sentence.split(separator: " ")`
let words = sentence.split(separator: " ")
// Print `words` to the console
print(words)
// Print "Word count: \(words.count)" to the console
print("Word count: \(words.count)")
Login to try C/C++/Java/PHP code in the editor
Replacing Substrings
.replacingOccurrences(of:with:) target substring की हर match को दूसरे से replace करके एक नई string return करता है।
उदाहरण: Replacing Substrings
// Import the `Foundation` module
import Foundation
// Declare a constant `text`, set to `"I like cats and cats like me"`
let text = "I like cats and cats like me"
// Declare a constant `replaced`, set to `text.replacingOccurrences(of: "cats", with: "dogs")`
let replaced = text.replacingOccurrences(of: "cats", with: "dogs")
// Print `replaced` to the console
print(replaced)
Login to try C/C++/Java/PHP code in the editor
Trimming Whitespace
.trimmingCharacters(in: .whitespacesAndNewlines) leading और trailing whitespace हटाता है, जो user input साफ़ करते समय आम है।
उदाहरण: Trimming Whitespace
// Import the `Foundation` module
import Foundation
// Declare a constant `messy`, set to `" hello swift "`
let messy = " hello swift "
// Declare a constant `trimmed`, set to `messy.trimmingCharacters(in: .whitespacesAndNewlines)`
let trimmed = messy.trimmingCharacters(in: .whitespacesAndNewlines)
// Print "[\(trimmed)]" to the console
print("[\(trimmed)]")
Login to try C/C++/Java/PHP code in the editor
- यह भूल जाना कि
.split(separator:)Substringका एक array return करता है,Stringनहीं, जो कुछ APIs के लिए मायने रख सकता है जो एक पूरीStringexpect करती हैं। - किसी string पर
String.Index-based APIs या.prefix()और.suffix()जैसे convenience methods के बजाय plain integer slicing उपयोग करने की कोशिश करना। .replacingOccurrences(of:with:)उपयोग करना और यह भूल जाना कि यह original को जगह पर modify करने के बजाय एक नई string return करता है।
.split(separator:)एक string को substrings के एक array में तोड़ता है।.replacingOccurrences(of:with:)matches replaced के साथ एक नई string return करता है।.prefix(n)और.suffix(n)सुरक्षित रूप से पहले या आखिरी n characters return करते हैं।.trimmingCharacters(in:)किसी string के ends से अनचाहे characters, आमतौर पर whitespace, हटाता है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: