Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the substring between braces?

I have a string as this.

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

How do I get the substring 53 ?

like image 881
Emmy Avatar asked Feb 19 '13 13:02

Emmy


Video Answer


3 Answers

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.

like image 178
iDroid Avatar answered Oct 19 '22 22:10

iDroid


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.

like image 38
Emmy Avatar answered Oct 19 '22 23:10

Emmy


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
like image 26
Nikola Lajic Avatar answered Oct 20 '22 00:10

Nikola Lajic