0

Input:

chris@mydomain.com
steve@mydomain.com

Output:

chris
steve

I'm looking to get the substring before the @ character. In Python, I would use something like: myString = myString[:myString.find("@")] but I think Swift's version is very complex, at least from what I've been reading. Would it be better to bridge to Obj-C in this case, since Swift's indexOf/find function looks something like this mess: Finding index of character in Swift String ?

Something like this, even though it's using arrays, seems to be the simpliest route:

contact = contact.componentsSeparatedByString("@")[0]
Community
  • 1
  • 1
user83039
  • 3,047
  • 5
  • 19
  • 31

5 Answers5

0

This may help you

let arr = split(contact, { $0 == "@"}, maxSplit: Int.max, allowEmptySlices: false)
println(arr[0])
Neenu
  • 6,848
  • 2
  • 28
  • 54
0

I believe you have hit the nail on the head. Another option is to use regular expressions to find it. I'm still learning swift, but the objective-c version of things is as follows:

-(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]];
}

This is in my opinion harder to read, but it has the added benefit of validating the email as you go.

Regex credit: Regex for email address

Community
  • 1
  • 1
0

And then there is this Obj-C snippet, which addresses more specifically the data given in the question. (Forgive that I have not translated to Swift, still working on that skill.)

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

In Swift, Python myString[:myString.find("@")] is equivalent to:

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

But this causes a runtime error unless myString contains "@".

This is safer.

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

Note that, find() searches Character only, not substring. so you cannot:

find(myString, "@mydomain")
rintaro
  • 51,423
  • 14
  • 131
  • 139
0

This works:

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

Output is "Hello"

JeremyP
  • 84,577
  • 15
  • 123
  • 161