-1

I can't seem to find the answer to this anywhere. I can do it in c but objective c is difficult.

I want to cut the end of a string after a certain character

so user@example.com will become user (cut at '@')

How do I do this?

shane
  • 1,742
  • 2
  • 19
  • 36
  • There are actually many ways to do this. I'm surprised that you find it easier in c. It can be done as one-liners in objective-c in at least two different ways. – CrimsonChris Jun 04 '14 at 01:41
  • Well mastering is different from c strings, so I'm not entire sure of the interface workings – shane Jun 04 '14 at 01:47

2 Answers2

9

This will give you the first chunk of text that comes before your special character.

NSString *separatorString = @"@";
NSString *myString = @"user@example.com";
NSString *myNewString = [myString componentsSeparatedByString:separatorString].firstObject;

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:

CrimsonChris
  • 4,651
  • 2
  • 19
  • 30
2

You can use a combination of substringToIndex: and rangeOfString: methods, like this:

NSString *str = @"user@example.com";
NSRange pos = [str rangeOfString:@"@"];
if (pos.location != NSNotFound) {
    NSString *prefix = [str substringToIndex:pos.location];
}

Notes:

  1. You need to check the location against NSNotFound to ensure that the position is valid.
  2. substringToIndex: excludes the index itself, so the @ character would not be included.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523