Your string format is very well-defined (as you say, the name you are after is always preceded by "/name_" and always followed by "_"), and I suppose that the name ("john") hence cannot contain an underscore.
I'd therefore consider a simple regular expression, which is perfectly suited for this sort of problem:
NSString *regexPattern = @"^.*/name_(.*?)_.*$";
NSString *name = [dataString stringByReplacingOccurrencesOfString: regexPattern
withString: @"$1"
options: NSRegularExpressionSearch
range: NSMakeRange(0, dataString.length)];
In case you are not familiar with regular expressions, what is going on here is:
- Begin at the beginning of the string (the "^")
- Allow anything (".*") followed by "/name_"
- Capture what follows (the parenthesis means "capture this")
- In the parenthesis, allow anything (".*"), but make it as short as possible (the "?" after the "*")
- It must be followed by an underscore and then allow anything that happens to be there up to the end of the string (the "$")
This will match the whole string, and when substituting the match (i.e., all of the string) with "$1", it will substitute the match with the substring included in the first (and only) parenthesis.
Result: It will produce a string that contains only the name. If the string does not have the correct format (i.e., no name between two underscores), then it will not change anything and return the full, original string.
It is a matter of coding style whether you prefer one approach over the other, but if you like regular expressions, then this approach is both clean, easy to understand and simple to maintain.
As I see it, any fragility in this is due to the data format, which looks suspiciously like something that depends on other "random" pieces of data, so whichever method you choose to parse that string, make sure you add some defensive tests to check the data format and alert you if unexpected strings begin to enter your data. This could be years from now, when you have forgotten everything about underscores, regexes and NSScanner
.