How can I substring in a required format in ios [duplicate] - ios

This question already has answers here:
How do you detect words that start with “#” or “#” within an NSString?
(6 answers)
Closed 7 years ago.
I have a string like this ,
NSString *strTest = #"Hii how are you doing #Ravi , how do u do #Kiran where are you #Varun";
I want a substring from the above string which contains only the words which starts with '#'
i.e I need
NSString *strSubstring = #"Ravi #kiran #varun";
Please help me out how could I achieve this

Separate the string like below :-
NSArray * names = [myString componentsSeparatedByString:#" "];
names array will now contain all the words in the string, now you can iterate over the array and check which of its index contains "#" character.
If you find "#", store that index value in some variable.

you will love implementing this code. I have used a regular expression to perform the job. It will give you the matching strings.
NSString *strTest = #"Hii how are you doing #Ravi , how do u do #Kiran where are you #Varun";
NSError *error;
//&[^;]*;
NSRegularExpression *exp =[NSRegularExpression regularExpressionWithPattern:#"#[^ ]*" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *s1= [exp matchesInString:strTest options:NSMatchingReportCompletion range:NSMakeRange(0, [strTest length]) ];
[s1 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSTextCheckingResult *result = obj;
NSString *str = [strTest substringWithRange:result.range];
NSLog(#"str %#",str);
}];

Related

How to trim string till first alphabet in a alphanumeric string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a alpha numeric string as 24 minutes i want to trim it like 24mplease tell me how can i do this ?
try use code in regex:
NSString *string = #"24 minutes";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"([0-9]+)[^a-zA-Z]*([a-zA-Z]{1}).*" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#"$1$2"];
NSLog(#"%#", modifiedString);
output:
24m
You can use the componentsSeparatedByString: and substringToIndex: methods of NSString Class, to achieve the result.
NSString *str = #"24 minutes";
NSArray *components = [str componentsSeparatedByString:#" "];
// Validation to prevent array out of index crash (If input is 24)
if ([components count] >= 2)
{
NSString *secondStr = components[1];
// Validation to prevent crash (If input is 24 )
if (secondStr.length)
{
NSString *shortName = [secondStr substringToIndex:1];
str = [NSString stringWithFormat:#"%#%#",components[0],shortName];
}
}
NSLog(#"%#",str);
This example works with the above string, however you need to take care of different type of inputs. It can fail if there is multiple spaces between those values.
NSString *aString = #"24 minutes"; // can be "1 minute" also.
First divide the string into two components:
Divide it with white space, since your string can contain one or more number also like "1 minute", "24 mintutes".
NSArray *array = [aString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
array = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF != ''"]];
NSLog(#"%#",[array objectAtIndex:0]);
Then fetch the first letter of the second component of the string using substringToIndex and finally combine both the strings.
NSString * firstLetter = [[array objectAtIndex:1] substringToIndex:1];
NSString *finalString = [[array objectAtIndex:0] stringByAppendingString:firstLetter];
NSLog(#"%#",finalString);

Understanding how to use NSRegularExpressions correctly

I am trying to write a function that has an NSString and parses it returning an array of tags.
The definition of a tag is any nsstring text that starts with # and contains only alphanumeric characters after the #.
Is this correct?
#.*?[A-Za-z0-9]
I want to use matchesInString:options:range: but need some help.
My function is:
- (void) getTags
{
NSString* str = #"This is my string and a couple of #tags for #you.";
// Range is 0 to 48 (full length of string)
// NSArray should contain #tags and #you only.
Thanks!
The patten "#.*?[A-Za-z0-9]" matches a # which is followed by zero or more
characters which are not in the set [A-Za-z0-9]. What you probably want is
NSString *pattern = #"#[A-Za-z0-9]+";
The you can create a regular expression using that pattern:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
and enumerate all matches in the string:
NSString *string = #"abc #tag1 def #tag2.";
NSMutableArray *tags = [NSMutableArray array];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, string.length)
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange range = [result range];
NSString *tag = [string substringWithRange:range];
[tags addObject:tag];
}];
NSLog(#"%#", tags);
Output:
(
"#tag1",
"#tag2"
)

iOS: extract substring of NSString in objective C

I have an NSString as:
"<a href='javascript:void(null)' onclick='handleCommandForAnchor(this, 10);return false;'>12321<\/a>"
I need to extract the 12321 near the end of the NSString from it and store.
First I tried
NSString *shipNumHtml=[mValues objectAtIndex:1];
NSInteger htmlLen=[shipNumHtml length];
NSString *shipNum=[[shipNumHtml substringFromIndex:htmlLen-12]substringToIndex:8];
But then I found out that number 12321 can be of variable length.
I can't find a method like java's indexOf() to find the '>' and '<' and then find substring with those indices. All the answers I've found on SO either know what substring to search for or know the location if the substring. Any help?
I don't usually advocate using Regular expressions for parsing HTML contents but it seems a regex matching >(\d+)< would to the job in this simple string.
Here is a simple example:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#">(\\d+)<"
options:0
error:&error];
// Handle error != nil
NSTextCheckingResult *match = [regex firstMatchInString:string
options:0
range:NSMakeRange(0, [string length])];
if (match) {
NSRange matchRange = [match rangeAtIndex:1];
NSString *number = [string substringWithRange:matchRange]
NSLog(#"Number: %#", number);
}
As #HaneTV says, you can use the NSString method rangeOfString to search for substrings. Given that the characters ">" and "<" appear in multiple places in your string, so you might want to take a look at NSRegularExpression and/or NSScanner.
that may help on you a bit, I've just tested:
NSString *_string = #"<a href='javascript:void(null)' onclick='handleCommandForAnchor(this, 10);return false;'>12321</a>";
NSError *_error;
NSRegularExpression *_regExp = [NSRegularExpression regularExpressionWithPattern:#">(.*)<" options:NSRegularExpressionCaseInsensitive error:&_error];
NSArray *_matchesInString = [_regExp matchesInString:_string options:NSMatchingReportCompletion range:NSMakeRange(0, _string.length)];
[_matchesInString enumerateObjectsUsingBlock:^(NSTextCheckingResult * result, NSUInteger idx, BOOL *stop) {
for (int i = 0; i < result.numberOfRanges; i++) {
NSString *_match = [_string substringWithRange:[result rangeAtIndex:i]];
NSLog(#"%#", _match);
}
}];

Regex in objective C

I want to extract only the names from the following string
bob!33#localhost #clement!17#localhost jack!03#localhost
and create an array [#"bob", #"clement", #"jack"].
I have tried NSString's componentsseparatedbystring: but it didn't work as expected. So I am planning to go for regEx.
How can I extract strings between ranges and add it to an array
using regEx in objective C?
The initial string might contain more than 500 names, would it be a
performance issue if I manipulate the string using regEx?
You can do it without regex as below (Assuming ! sign have uniform pattern in your all words),
NSString *names = #"bob!33#localhost #clement!17#localhost jack!03#localhost";
NSArray *namesarray = [names componentsSeparatedByString:#" "];
NSMutableArray *desiredArray = [[NSMutableArray alloc] initWithCapacity:0];
[namesarray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSRange rangeofsign = [(NSString*)obj rangeOfString:#"!"];
NSString *extractedName = [(NSString*)obj substringToIndex:rangeofsign.location];
[desiredArray addObject:extractedName];
}];
NSLog(#"%#",desiredArray);
output of above NSLog would be
(
bob,
"#clement",
jack
)
If you still want to get rid of # symbol in above string you can always replace special characters in any string, for that check this
If you need further help, you can always leave comment
NSMutableArray* nameArray = [[NSMutableArray alloc] init];
NSArray* youarArray = [yourString componentsSeparatedByString:#" "];
for(NSString * nString in youarArray) {
NSArray* splitObj = [nString componentsSeparatedByString:#"!"];
[nameArray addObject:[splitObj[0]]];
}
NSLog(#"%#", nameArray);
I saw the other solutions and it seemed no one tried to use real regular expressions here, so I created a solution which uses it, maybe you or someone else can use it as a possible idea in the future:
NSString *_names = #"bob!33#localhost #clement!17#localhost jack!03#localhost";
NSError *_error;
NSRegularExpression *_regExp = [NSRegularExpression regularExpressionWithPattern:#" ?#?(.*?)!\\d{2}#localhost" options:NSRegularExpressionCaseInsensitive error:&_error];
NSMutableArray *_namesOnly = [NSMutableArray array];
if (!_error) {
NSLock *_lock = [[NSLock alloc] init];
[_regExp enumerateMatchesInString:_names options:NSMatchingReportProgress range:NSMakeRange(0, _names.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
if (result.numberOfRanges > 1) {
if ([_lock tryLock]) [_namesOnly addObject:[_names substringWithRange:[result rangeAtIndex:1]]], [_lock unlock];
}
}];
} else {
NSLog(#"error : %#", _error);
}
the result can be logged...
NSLog(#"_namesOnly : %#", _namesOnly);
...and that will be:
_namesOnly : (
bob,
clement,
jack
)
Or even something as simple as this will do the trick:
NSString *strNames = #"bob!33#localhost #clement!17#localhost jack!03#localhost";
strNames = [[strNames componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]]
componentsJoinedByString:#""];
NSArray *arrNames = [strNames componentsSeparatedByString:#"localhost"];
NSLog(#"%#", arrNames);
Output:
(
bob,
clement,
jack,
""
)
NOTE: Ignore the last element index while iterating or whatever
Assumption:
"localhost" always comes between names
I know it ain't so optimized but it's one way to do this

componentsSeperatedByString returns full word [duplicate]

This question already has answers here:
Is there a simple way to split a NSString into an array of characters?
(4 answers)
Closed 9 years ago.
I am trying to get each letter of an NSString using this line of code:
NSArray *array = [string componentsSeparatedByString:#""];
//string is equal to Jake
NSLog(#"Array Count:%d",[array count]);
I am expecting to get each letter of the word "Jake" but instead I am getting the whole word. Why?
From Apple's Doc about this method
NSString *list = #"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:#", "];
produces an array { #"Norman", #"Stanley", #"Fletcher" }.
So empty separator will not separate each character of string, this
method doesn't work this way.
Here is an answer for your question
How to convert NSString to NSArray with characters one by one in Objective-C
The idea of separating a string by nothing doesn't logically make sense, it is like trying to divide by zero.
But to answer the question:
NSMutableArray *stringComponents = [NSMutableArray arrayWithCapacity:[string length]];
for (int i = 0; i < [string length]; i++) {
NSString *character = [NSString stringWithFormat:#"%c", [string characterAtIndex:i]];
[stringComponents addObject:character];
}`

Resources