6

I have a string as this.

NSString *myString = @"{53} balloons";

How do I get the substring 53 ?

Emmy
  • 3,949
  • 5
  • 28
  • 30
  • 1
    Emmy, are you looking to search for it in the string or do you know the location of the string already (position 1) and you just want to extract it into another string. – Khaled Barazi Feb 19 '13 at 13:55
  • If you're simply looking to extract the substring between braces, I endorse @iDroid's answer. If you're after more complex searching, take a look at this: http://stackoverflow.com/questions/4353834/search-through-nsstring-using-regular-expression. Though obviously bear in mind the resource costs of using this approach. – sam-w Feb 19 '13 at 14:08
  • No. I don't know the location of 53, the myString will be the random string generated by the engine. I need to get 53 between {} as the answer. But I already figure out how to do it now. See my answer below. – Emmy Feb 20 '13 at 08:05

10 Answers10

18
NSString *myString = @"{53} balloons";
NSRange start = [myString rangeOfString:@"{"];
NSRange end = [myString rangeOfString:@"}"];
if (start.location != NSNotFound && end.location != NSNotFound && end.location > start.location) {
    NSString *betweenBraces = [myString substringWithRange:NSMakeRange(start.location+1, end.location-(start.location+1))];
}

edit: Added range check, thx to Keab42 - good point.

iDroid
  • 10,403
  • 1
  • 19
  • 27
  • 1
    You should check that the two ranges aren't NSNotFound and that end.location > start.location – Keab42 Feb 19 '13 at 14:07
  • 1
    Thanks for the nice answer. Here is what I did: NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:@"{}"]; NSArray *splitString = [myString componentsSeparatedByCharactersInSet:delimiters]; NSString *substring = [splitString objectAtIndex:1]; the substring is 53. – Emmy Feb 20 '13 at 07:58
6

Here is what I did.

NSString *myString = @"{53} balloons";
NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:@"{}"];
NSArray *splitString = [myString componentsSeparatedByCharactersInSet:delimiters];
NSString *substring = [splitString objectAtIndex:1];

the substring is 53.

Emmy
  • 3,949
  • 5
  • 28
  • 30
2

You can use a regular expression to get the number between the braces. It might seem a bit complicated but the plus side is that it will find multiple numbers and the position of the number doesn't matter.

Swift 4.2:

let searchText = "{53} balloons {12} clowns {123} sparklers"
let regex = try NSRegularExpression(pattern: "\\{(\\d+)\\}", options: [])
let matches = regex.matches(in: searchText, options: [], range: NSRange(searchText.startIndex..., in: searchText))
matches.compactMap { Range($0.range(at: 1), in: searchText) }
       .forEach { print("Number: \(searchText[$0])") }

Objective-C:

NSString *searchText = @"{53} balloons {12} clowns {123} sparklers";

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{(\\d+)\\}" 
                                                                       options:0 
                                                                         error:nil];

NSArray *matches = [regex matchesInString:searchText 
                                  options:0 
                                    range:NSMakeRange(0, searchText.length)];

for (NSTextCheckingResult *r in matches)
{
    NSRange numberRange = [r rangeAtIndex:1];
    NSLog(@"Number: %@", [searchText substringWithRange:numberRange]);
}

This will print out:

Number: 53
Number: 12
Number: 123
Nikola Lajic
  • 3,985
  • 28
  • 34
2

For Swift 4.2:

if let r1 = string.range(of: "{")?.upperBound,
let r2 = string.range(of: "}")?.lowerBound {
    print (String(string[r1..<r2]))
}
Łukasz
  • 773
  • 5
  • 23
1

Try this code.

 NSString *myString = @"{53} balloons";
 NSString *value = [myString substringWithRange:NSMakeRange(1,2)];
Vinayak Kini
  • 2,919
  • 21
  • 35
  • 8
    And what will you do on a happy day when you get 100 baloons? – Vladimir Feb 19 '13 at 14:02
  • Why not just: `NSString *value = @"53";`? – trojanfoe Feb 19 '13 at 14:03
  • I think she asked for a single string! – Vinayak Kini Feb 19 '13 at 14:03
  • 1
    @trojanfoe - based on the information provided by the OP, his response is just fine. If the OP wants flexibility, she will need to indicate that her format isn't static. All we know is that she has a single string and simply wants 53 extracted from it. You are welcome to spend your valuable time providing a flexible-reusable method. – Jeremy Feb 19 '13 at 14:03
  • 1
    @Jeremy I disagree. The question is flawed, sure, but it's pretty obvious that the OP wants a generalised solution where the brackets are considered, not merely the position of the text "53". – trojanfoe Feb 19 '13 at 14:05
  • @trojanfoe Its not specified in the question that strings may change!! so my answer is valid. – Vinayak Kini Feb 19 '13 at 14:05
  • myString is the string that generated randomly from my engine. So the position of {} and the number between {} will be different in myString every time when I call to get new myString. – Emmy Feb 20 '13 at 08:11
1

For Swift 2.1 :-

var start = strData?.rangeOfString("{")
var end = strData?.rangeOfString("}")
if (start!.location != NSNotFound && end!.location != NSNotFound && end!.location > start!.location) {
    var betweenBraces = strData?.substringWithRange(NSMakeRange(start!.location + 1, end!.location-(start!.location + 1)))
    print(betweenBraces)
}
chengsam
  • 7,315
  • 6
  • 30
  • 38
Irshad Qureshi
  • 807
  • 18
  • 41
0

I guess, your a looking for the NSScanner class, at least if you are addressing a general case. Have a look in Apples documentation.

Matthias
  • 8,018
  • 2
  • 27
  • 53
0

Search the location for "{" and "}". Take substring between those index.

Apurv
  • 17,116
  • 8
  • 51
  • 67
0

Checked with any number of data:

  NSString *str = @"{53} balloons";
    NSArray* strary = [str componentsSeparatedByString: @"}"];
    NSString* str1 = [strary objectAtIndex: 0];
    NSString *str2 = [str1 stringByReplacingOccurrencesOfString:@"{" withString:@""];
    NSLog(@"number = %@",str2);

Another method is

NSString *tmpStr = @"{53} balloons";
NSRange r1 = [tmpStr rangeOfString:@"{"];
NSRange r2 = [tmpStr rangeOfString:@"}"];
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
NSString *subString = [tmpStr substringWithRange:rSub];
Dilip Manek
  • 9,095
  • 5
  • 44
  • 56
-1

If you don't know how many digits there will be, but you know it will always be enclosed with curly braces try this:

NSString *myString = @"{53} balloons";
NSRange startRange = [myString rangeOfString:@"{"];
NSRange endRange = [myString rangeOfString:@"}"];
if (startRange.location != NSNotFound && endRange.location != NSNotFound && endRange.location > startRange.location) {
    NSString *value = [myString substringWithRange:NSMakeRange(startRange.location,endRange.ocation - startRange.location)];
}

There's probably a more efficient way to do it though.

Keab42
  • 688
  • 13
  • 28