Check if there is a word after a word (NSSTRING) - ios

I have a fun little tricky problem. So I need to create an if statement that can detect if there is a word after a word in an array
so my code is
NSArray *words = [texfield.text componentsSeparatedByString:#" "];
int index = [words indexOfObject:#"string"];
I am not sure if I have to do something like
NSString*needle=words[index+1];
if (needle isEqualto #"") {
//There is a word after #"string";
}
What should I do?
How can I determine is there is a word after #"string"?
I appreciate all the help!! :)

Yeah, you have to:
NSArray *words = [texfield.text componentsSeparatedByString:#" "];
NSInteger index = [words indexOfObject:#"string"];
NSInteger afterIndex = index+1;
if(afterIndex<words.count) {
NSString *needle = words[index+1];
if (needle isEqualToString #"") {
//do something
}
}

NSString *yourString = #"string stackoverflow word after string regex";
NSRange yourStringRange = NSMakeRange(0, [yourString length]);
NSString *pattern = #"string\\s*([^\\s]*)";
NSError *error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern options:0 error:&error];
NSArray* matches = [regex matchesInString:yourString options:0 range: yourStringRange];
for (NSTextCheckingResult* match in matches) {
NSRange rangeForMatch = [match rangeAtIndex:1];
NSLog(#"word after STRING: %#", [yourString substringWithRange:rangeForMatch]);
}
Output:
word after STRING: stackoverflow
word after STRING: regex

Method componentsSeparatedByString: will give all components separated by input NSString.
Your eg. NSArray *words = [texfield.text componentsSeparatedByString:#" "];
will have all string separated by " ". So just check if any
NSInteger afterIndex = index+1;
if(afterIndex<words.count) if Yes, you have NSStringavailable.

Related

Use regular expression to find and replace the string from Textfield in NSString

I would like to use regular expression to find and replace the string. In my scenario {3} and {2} are UITextField tag values. Based on the tag value, I would like to replace the respective textfield values and calculate the string value using NSExpression.
Sample Input String :
NSString *cumputedValue = #"{3}*0.42/({2}/100)^2";
Note: The textFields are created dynamically based on JSON response.
I got the answer for this question. Here the computedString contains the value as "{3}*0.42/({2}/100)^2".
- (NSString *)autoCalculationField: (NSString *)computedString {
NSString *computedStringFormula = [NSString stringWithFormat:#"%#",computedString];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\{(\\d+)\\}"
options:0
error:nil];
NSArray *matches = [regex matchesInString:computedStringFormula
options:0
range:NSMakeRange(0, computedStringFormula.length)];
NSString *expressionStr = computedStringFormula;
for (NSTextCheckingResult *r in matches)
{
NSRange numberRange = [r rangeAtIndex:1];
NSString *newString = [NSString stringWithFormat:#"%.2f",[self getInputFieldValue:[computedStringFormula substringWithRange:numberRange]]];
expressionStr = [expressionStr stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"{%#}",[computedStringFormula substringWithRange:numberRange]] withString:newString];
}
NSExpression *expression = [NSExpression expressionWithFormat:expressionStr];
return [expression expressionValueWithObject:nil context:nil];
}
- (float)getInputFieldValue: (NSString *)tagValue {
UITextField *tempTextFd = (UITextField *)[self.view viewWithTag:[tagValue intValue]];
return [tempTextFd.text floatValue];
}
You could save the textField tags in a NSDictionary with the value that they represent.
After that use stringByReplacingOccurrencesOfString to replace the values that you wish to.
Something like this:
for (NSString *key in dict) {
cumputedValue = [cumputedValue stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"{#%}", key] withString:[NSString stringWithFormat:#"%#", dict objectForKey:#key]];
}
This way you can have the values replaced

How to add a character at start and end of every word in NSString

Suppose i have this:
NSString *temp=#"its me";
Now suppose i want ' " ' in start and end of every word, how can i achieve it to get the result like this:
"its" "me"
Do i have to use regular expressions?
If you have punctuation inside the string, splitting with a space might not be enough.
Use the word boundary \b: it matches both the leading and trailing word boundaries (that is, it will match an empty space right between word and non-word characters and also at the start/end of the string if followed/preceded with a word character.
NSError *error = nil;
NSString *myText = #"its me";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\b" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:#"\""];
NSLog(#"%#", modifiedString); // => "its" "me"
See the IDEONE demo
See more details on the regex syntax in Objective C here.
You can do something like,
NSString *str = #"its me";
NSMutableString *resultStr = [[NSMutableString alloc]init];
NSArray *arr = [str componentsSeparatedByString:#" "];
for (int i = 0; i < arr.count; i++) {
NSString *tempStr = [NSString stringWithFormat:#"\"%#\"",arr[i]];
resultStr = [resultStr stringByAppendingString:[NSString stringWithFormat:#"%# ",tempStr]];
}
NSLog(#"result string is : %#",resultStr);
Hope this will help :)

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);
}
}];

How to get all strings inside [...] in one NSString?

Say given an NSString:
#"[myLabel]-10-[youImageView]"
I need an array of:
#[#"myLabel", #"yourImageView"]
How do I do it?
I thought about going through the string and check each '[' and ']', get string inside them, but is there any other better way?
Thanks
You can use regular expressions:
NSString *string = #"[myLabel]-10-[youImageView]";
// Regular expression to find "word characters" enclosed by [...]:
NSString *pattern = #"\\[(\\w+)\\]";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:NULL];
NSMutableArray *list = [NSMutableArray array];
[regex enumerateMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
// range = location of the regex capture group "(\\w+)" in the string:
NSRange range = [result rangeAtIndex:1];
[list addObject:[string substringWithRange:range]];
}
];
NSLog(#"%#", list);
Output:
(
myLabel,
youImageView
)
Would this work for you?
NSCharacterSet *aSet = [NSCharacterSet characterSetWithCharactersInString:#"]-10["];
NSArray *anArray = [aString componentsSeparatedByCharactersInSet:aSet];

Finding first letter in NSString and counting backwards

I'm new to IOS, and was looking for some guidance.
I have a long NSString that I'm parsing out. The beginning may have a few characters of garbage (can be any non-letter character) then 11 digits or spaces, then a single letter (A-Z). I need to get the location of the letter, and get the substring that is 11 characters behind the letter to 1 character behind the letter.
Can anyone give me some guidance on how to do that?
Example: '!!2553072 C'
and I want : '53072 '
You can accomplish this with the regex pattern: (.{11})\b[A-Z]\b
The (.{11}) will grab any 11 characters and the \b[A-Z]\b will look for a single character on a word boundary, meaning it will be surrounded by spaces or at the end of the string. If characters can follow the C in your example then remove the last \b. This can be accomplished in Objective-C like so:
NSError *error;
NSString *example = #"!!2553072 C";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(.{11})\\b[A-Z]\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
if(!regex)
{
//handle error
}
NSTextCheckingResult *match = [regex firstMatchInString:example
options:0
range:NSMakeRange(0, [example length])];
if(match)
{
NSLog(#"match: %#", [example substringWithRange:[match rangeAtIndex:1]]);
}
There may be a more elegant way to do this involving regular expressions or some Objective-C wizardry, but here's a straightforward solution (personally tested).
-(NSString *)getStringContent:(NSString *)input
{
NSString *substr = nil;
NSRange singleLetter = [input rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(singleLetter.location != NSNotFound)
{
NSInteger startIndex = singleLetter.location - 11;
NSRange substringRange = NSMakeRange(start, 11);
substr = [tester substringWithRange:substringRange];
}
return substr;
}
You can use NSCharacterSets to split up the string, then take the first remaining component (consisting of your garbage and digits) and get a substring of that. For example (not compiled, not tested):
- (NSString *)parseString:(NSString *)myString {
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
NSArray *components = [myString componentsSeparatedByCharactersInSet:letters];
assert(components.count > 0);
NSString *prefix = components[0]; // assuming relatively new Xcode
return [prefix substringFromIndex:(prefix.length - 11)];
}
//to get rid of all non-Digits in a NSString
NSString *customerphone = CustomerPhone.text;
int phonelength = [customerphone length];
NSRange customersearchRange = NSMakeRange(0, phonelength);
for (int i =0; i < phonelength;i++)
{
const unichar c = [customerphone characterAtIndex:i];
NSString* onechar = [NSString stringWithCharacters:&c length:1];
if(!isdigit(c))
{
customerphone = [customerphone stringByReplacingOccurrencesOfString:onechar withString:#"*" options:0 range:customersearchRange];
}
}
NSString *PhoneAllNumbers = [customerphone stringByReplacingOccurrencesOfString:#"*" withString:#"" options:0 range:customersearchRange];

Resources