How to parse a string format like [***]***? - objective-c

I need to parse a string like [abc]000, and what I want to get is an array containing abc and 000. Is there an easy way to do it?
I'm using code like this:
NSString *sampleString = #"[abc]000";
NSArray *sampleParts = [sampleString componentsSeparatedByString:#"]"];
NSString *firstPart = [[[sampleParts objectAtIndex:0] componentsSeparatedByString:#"["] lastObject];
NSString *lastPart = [sampleParts lastObject];
But it's inefficient and didn't check whether the string is in a format like [**]**.

For this simple pattern, can just parse yourself like:
NSString *s = #"[abc]000";
NSString *firstPart = nil;
NSString *lastPart = nil;
if ([s characterAtIndex: 0] == '[') {
NSUInteger i = [s rangeOfString:#"]"].location;
if (i != NSNotFound) {
firstPart = [s substringWithRange:NSMakeRange(1, i - 1)];
lastPart = [s substringFromIndex:i + 1];
}
}
Or you could learn to use the NSScanner class.

As always, there are lots of ways to do this.
OPTION 1
If these are fixed length strings (each part is always three characters) then you can simply get the substrings directly:
NSString *sampleString = #"[abc]000";
NSString *left = [sampleString substringWithRange:NSMakeRange(1, 3)];
NSString *right = [sampleString substringWithRange:NSMakeRange(5, 3)];
NSArray *parts = #[ left, right ];
NSLog(#"%#", parts);
OPTION 1 (shortened)
NSArray *parts = #[ [sampleString substringWithRange:NSMakeRange(1, 3)],
[sampleString substringWithRange:NSMakeRange(5, 3)] ];
NSLog(#"%#", parts);
OPTION 2
If they aren't always three characters, then you can use NSScanner:
NSString *sampleString = #"[abc]000";
NSScanner *scanner = [NSScanner scannerWithString:sampleString];
// Skip the first character if we know that it will always start with the '['.
// If we can not make this assumption, then we would scan for the bracket instead.
scanner.scanLocation = 1;
NSString *left, *right;
// Save the characters until the right bracket into a string which we store in left.
[scanner scanUpToString:#"]" intoString:&left];
// Skip the right bracket
scanner.scanLocation++;
// Scan to the end (You can use any string for the scanUpToString that doesn't actually exist...
[scanner scanUpToString:#"\0" intoString:&right];
NSArray *parts = #[ left, right ];
NSLog(#"%#", parts);
RESULTS (for all options)
2013-05-10 00:25:02.031 Testing App[41906:11f03] (
abc,
000
)
NOTE
All of these assume well-formed strings, so you should include your own error checking.

try like this ,
NSString *sampleString = #"[abc]000";
NSString *pNRegex = #"\\[[a-z]{3}\\][0-9]{3}";
NSPredicate *PNTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", pNRegex];
BOOL check=[PNTest evaluateWithObject:sampleString ];
NSLog(#"success:%i",check);
if success comes as 1 then you can perform the action for separating string into array.

Related

How to get phone number from string?

I want to extract the phone number from a NSString.
For ex: In the string Nandu # +91-(123)-456-7890, I want to extract +91-(123)-456-7890.
I have tried code like,
NSString *myString = #"Nandu # +91-(123)-456-7890";
NSString *myRegex = #"\\d{2}+\\d{3}-\\d{3}-\\d{4}";
NSRange range = [myString rangeOfString:myRegex options:NSRegularExpressionSearch];
NSString *phoneNumber = nil;
if (range.location != NSNotFound) {
phoneNumber = [myString substringWithRange:range];
NSLog(#"%#", phoneNumber);
} else {
NSLog(#"No phone number found");
}
how can I get phone number with +91 also.
You can use this Regex pattern
(\+\d{2}-\(\d{3}\)-\d{3}-\d{4})
https://regexr.com/3qcsi
Using NSCharacterSet you can get your output. see below code and let me know if you have any query then.
NSString *originalString = #"Nandu # +91-(123)-456-7890";
NSString *cleanedString = [[originalString componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:#"0123456789-+()"] invertedSet]] componentsJoinedByString:#""];
NSLog(#"%#", cleanedString); //+91-(123)-456-7890
You can use componentsSeparatedByString
NSString *originalString = #"Nandu # +91-(123)-456-7890";
NSArray *arrayWithTwoStrings = [originalString componentsSeparatedByString:#"+"];
NSString *mobileNumberstring = [NSString stringWithFormat:#"+%#",[arrayWithTwoStrings objectAtIndex:1]];
NSLog (#"%#",mobileNumberstring);

How to remove the first space from the NSString?

I want to remove only first space in below string.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
Note: There is a space after IF_Distance and another space after
GET_Mi. I am unable to remove the space after IF_Distance.
Use rangeOfString: to locate the first space, then use stringByReplacingCharactersInRange:withString: to replace it with the empty string.
Remove space by using below code.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *secondString = [str stringByReplacingOccurrencesOfString:#"IF_Distance " withString:#"IF_Distance"];
Try This:
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *firstStringContainingSpace = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject];//firstStringContainingSpace = IF_Distance
str = [str stringByReplacingCharactersInRange:[str rangeOfString:[NSString stringWithFormat:#"%# ",firstStringContainingSpace]] withString:firstStringContainingSpace];
Output:
str = #"IF_Distance(GET_Mi mi=km*1.4,STRING1,STRING2)";
You can remove first space by using following code:
First find space by using rangeOfString: and then remove by using stringByReplacingCharactersInRange:withString: method.
Like,
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *strSpace = #" ";
NSRange range = [str rangeOfString:strSpace];
NSString *strFinal;
if (NSNotFound != range.location) {
strFinal = [str stringByReplacingCharactersInRange:range withString:#""];
}
If you are looking for some more universal way - this is the variant of it:
- (NSString *)removeWhitespaces:(NSString *)string {
NSMutableArray * stringComponents = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
NSString * fStringComponent = [stringComponents firstObject];
[stringComponents removeObject:fStringComponent];
return [fStringComponent stringByAppendingString:[stringComponents componentsJoinedByString:#" "]];
}

Obj-C: Create Array From String Where items are in <>

I am trying to parse a String to an Array each item is between <> for example <this is column 1><this is column 2> etc....
Help would be much appreciated.
Thanks
Something to demonstrate:
NSString *string = #"<this is column 1><this is column 2>";
NSScanner *scanner = [NSScanner scannerWithString:string];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
NSString *temp;
while ([scanner isAtEnd] == NO)
{
// Disregard the result of the scanner because it returns NO if the
// "up to" string is the first one it encounters.
// You should still have this in case there are other characters
// between the right and left angle brackets.
(void) [scanner scanUpToString:#"<" intoString:NULL];
// Scan the left angle bracket to move the scanner location past it.
(void) [scanner scanString:#"<" intoString:NULL];
// Attempt to get the string.
BOOL success = [scanner scanUpToString:#">" intoString:&temp];
// Scan the right angle bracket to move the scanner location past it.
(void) [scanner scanString:#">" intoString:NULL];
if (success == YES)
{
[array addObject:temp];
}
}
NSLog(#"%#", array);
NSString *input =#"<one><two><three>";
NSString *strippedInput = [input stringByReplacingOccurencesOfString: #">" withString: #""]; //strips all > from input string
NSArray *array = [strippedInput componentsSeperatedByString:#"<"];
Note that [array objectAtIndex:0] will be an empty string ("") an this doesn't work of course, if one of the "actual" string contain < or >
One approach might be to use either componentsSeparatedByCharactersInSet or componentsSeparatedByString from NSString.
NSString *test = #"<one> <two> <three>";
NSArray *array1 = [test componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
NSArray *array2 = [test componentsSeparatedByString:#"<"];
You'll need to do some cleaning up afterward, either trimming in the case of array2 or removing white-space strings in the case of array1

Formatting a String in Objective - C

I'm getting a response from webservice as a string like below one -
brand=company%%samsung##modelnumber=webmodel%%GT1910##Sim=Single%%SingleSim##3g=yes%%Yes##wifi=yes%%yes(2.1 mbps upto)
I'm confusing that to format my response like below one -
brand=samsung
modelnumber=GT1910
Sim=SingleSim
3g=Yes
wifi=(2.1 mbps upto)
I've tried to remove the special characters (## and %%)
specialString = [specialString stringByReplacingOccurrencesOfString:#"##" withString:#"\n"];
specialString = [specialString stringByReplacingOccurrencesOfString:#"%%" withString:#"\n"];
specialString= [specialString stringByReplacingOccurrencesOfString:#" " withString:#""];
My output was -
brand=company
samsung
modelnumber=webmodel
GT1910
Sim=Single
SingleSim
3g=yes
Yes
wifi=yes
(2.1 mbps upto)
How to remove unwanted words.
You can't use simple find and replace because there are parts of the original string you don't want.
Untested, but this will probably work:
NSArray *parts = [specialstring componentsSeparatedByString:#"##"];
NSMutableArray *result = [[NSMutableArray alloc] init];
for(NSString *piece in parts) {
NSArray *pairs = [piece componentsSeparatedByString:#"="];
if([pairs count] > 1) {
NSString *key = [pairs objectAtIndex:0];
NSString *values = [pairs objectAtIndex:1];
NSArray *avalues = [values componentsSeparatedByString:#"%%"];
[result addObject:[NSString stringWithFormat:#"%#=%#", key, [avalues lastObject]]];
}
}
NSLog(#"%#", [result componentsJoinedByString:#"\n"]);
// [result release]; // Uncomment if ARC is turned off
First splits by ## and iterates over array. Then splits by = to get key on left side (index 0). Takes right side (index 1) and splits by %% and uses last value.
Trim like below it will work
NSString *strRes = #"brand=company%%samsung##modelnumber=webmodel%%GT1910##Sim=Single%%SingleSim##3g=yes%%Yes##wifi=yes%%yes(2.1 mbps upto)";
strRes = [strRes stringByReplacingOccurrencesOfString:#"=" withString:#"--"];
strRes = [strRes stringByReplacingOccurrencesOfString:#"##" withString:#"\n"];
NSRange rangeForTrim;
while ((rangeForTrim = [strRes rangeOfString:#"--[^%%]+%%" options:NSRegularExpressionSearch]).location != NSNotFound)
strRes = [strRes stringByReplacingCharactersInRange:rangeForTrim withString:#"="];
NSLog(#"%#",strRes);
Well, I can't write the code right away but here's what you gotta do:
Replace all %% with (space)
Replace all ## with \n
Remove all words between = and (space)

how to match string portion with NSArray values in objective-c

I have following array and search string.
NSArray *values =[NSArray arrayWithObjects:#"abc",#"xyz",#"cba",#"yzx",nil];
NSString *search = #"startcba";
I want to search string's end part within an array elements. My expected search result will be #"cba". Please let me know how to find the desire value in array for giving search.
Thanks,
You can use NSPredicate to get the elements that satisfy your requirement.
NSPredicate * predicate = [NSPredicate predicateWithFormat:#" %# ENDSWITH SELF ", search];
NSArray * searchResults = [values filteredArrayUsingPredicate:predicate];
The NSPredicates way is great.
Here is an approach with rangeOfString:
NSArray *values =[NSArray arrayWithObjects:#"abc",#"xyz",#"cba",#"yzx",nil];
NSString *search = #"startcba";
NSUInteger searchLength = [search length];
NSString *result = nil;
for (NSString *val in values)
{
NSUInteger valLength = [val length];
NSRange expectedRange = NSMakeRange(searchLength - valLength, valLength);
NSRange rng = [search rangeOfString:val];
if ( rng.location == expectedRange.location && rng.length == expectedRange.length )
{
result = val;
break;
}
}