2014-11-17 54 views
0

輸入:解析字符串:before字符串的字符

[email protected] 
[email protected] 

輸出:

chris 
steve 

我期待得到@字符前的子字符串。在Python中,我會使用類似於:myString = myString[:myString.find("@")],但我認爲Swift的版本非常複雜,至少從我讀過的內容來看。在這種情況下橋接Obj-C會更好嗎,因爲Swift的indexOf/find函數看起來像這樣的混亂:Finding index of character in Swift String

這樣的事情,即使它使用數組,似乎是simpliest路線:

contact = contact.componentsSeparatedByString("@")[0] 
+1

沒有錯,你提出的解決方案。 – CuriousRabbit

回答

0

在斯威夫特,巨蟒myString[:myString.find("@")]相當於:

myString[myString.startIndex ..< find(myString, "@")!] 

但是,這會導致運行錯誤,除非myString包含"@"

這樣更安全。

if let found = find(myString, "@") { 
    myString = myString[myString.startIndex ..< found] 
} 

需要注意的是,find()搜索Character只,而不是子串。所以你不能:

find(myString, "@mydomain") 
0

這可能會幫助你

let arr = split(contact, { $0 == "@"}, maxSplit: Int.max, allowEmptySlices: false) 
println(arr[0]) 
0

相信你已經擊中了要害。另一種選擇是使用正則表達式來查找它。我還在學習迅速,但對事物的Objective-C的版本如下:

-(NSString*) parseEmailPrefix(NSString*)email{ 
    NSError *error = nil; 
    NSString *pattern = @"([A-Z0-9a-z._%+-]+)@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
    NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern 
                      options:0 
                       error:&error]; 
    NSTextCheckingResult *result = [expression firstMatchInString:email 
                 options:0 
                 range:NSMakeRange(0, email.length)]; 
    return [string substringWithRange:[result rangeAtIndex:1]]; 
} 

這在我看來是難讀,但它作爲你去驗證電子郵件的好處。

正則表達式信用:Regex for email address

0

再有就是這個對象 - 片段,其中涉及更具體的問題給出的數據。 (請原諒,我還沒有翻譯成斯威夫特,在該技術仍然工作)

NSString* email = @"[email protected]"; 
NSURL* theURL = [NSURL URLWithString:[NSString stringWithFormat:@"mailto://%@", email]]; 
NSLog(@"%@ at %@", theURL.user, theURL.host); // yields "chuck at norris.net" 
0

這工作:

var str: String = "[email protected]" 
let a = str.componentsSeparatedByString("@") 
println("\(a[0])") 

輸出爲 「你好」