Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีแทนที่ตัวอักษรใน String ด้วย Objective-C

ใช้เมธอด stringByReplacingOccurrencesOfString:withString: ของ NSString

โค้ดตัวอย่าง

NSString *str = @"tutori@als";

// แทนที่ @ ด้วย ว่าง (ลบ @ ออก)
str = [str stringByReplacingOccurrencesOfString:@"@" withString:@""];

NSLog(@"%@", str); // ผลลัพธ์: "tutorials"

ตัวเลือกเพิ่มเติม

// Case insensitive
[str stringByReplacingOccurrencesOfString:@"@" 
                               withString:@""
                                  options:NSCaseInsensitiveSearch
                                    range:NSMakeRange(0, str.length)];

// แทนที่หลายตัวพร้อมกัน (iOS 9+)
[str stringByReplacingOccurrencesOfString:@"@" 
                               withString:@""
                                  options:[.caseInsensitive, .regularExpression]
                                    range:NSMakeRange(0, str.length)];

Swift Equivalent

var str = "tutori@als"
str = str.replacingOccurrences(of: "@", with: "")
print(str) // "tutorials"

// Regex replacement
let regexStr = "Hello 123 World 456"
let replaced = regexStr.replacingOccurrences(of: "\\d+", with: "#", options: .regularExpression)
// "Hello # World #"

กรณีใช้งานทั่วไป

  • ลบตัวอักษรพิเศษออกจาก Input
  • Format หมายเลขโทรศัพท์
  • Sanitize HTML/String
  • Replace Placeholder ใน Template