Objective-C, rangeOfString from an offset - objective-c

is it possible to use the method rangeOfString to search for a NSString starting from a given offset?
Something more similar to the strpos function in PHP.
Thanks

Not -rangeOfString:, but a similar method - -rangeOfString:options:range:.
(Edit: An example)
NSString *string = #"YaddaYaddaYadda";
NSString *searchString = #"Yadda";
NSRange thisCharRange, searchCharRange;
searchCharRange = NSMakeRange(3, [string length]);
thisCharRange = [string rangeOfString:searchString options:0 range:searchCharRange];
NSLog(#"thisCharRange: %#", NSStringFromRange(thisCharRange));

I find a problem with the example up there. It'll cause "Range or index out of bounds".
searchCharRange = NSMakeRange(3, [string length]);
should change to
searchCharRange = NSMakeRange(3, [string length] - 3);
that is,the range's length should not be longer than the original string's length - the range's start location.

Related

Take all numbers separated by spaces from a string and place in an array

I have a NSString formatted like this:
"Hello world 12 looking for some 56"
I want to find all instances of numbers separated by whitespace and place them in an NSArray. I dont want to remove the numbers though.
Whats the best way of achieving this?
This is a solution using regular expression as suggested in the comment.
NSString *string = #"Hello world 12 looking for some 56";
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:#"\\b\\d+" options:nil error:nil];
NSArray *matches = [expression matchesInString:string options:nil range:(NSMakeRange(0, string.length))];
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSTextCheckingResult *match in matches) {
[result addObject:[string substringWithRange:match.range]];
}
NSLog(#"%#", result);
First make an array using NSString's componentsSeparatedByString method and take reference to this SO question. Then iterate the array and refer to this SO question to check if an array element is number: Checking if NSString is Integer.
I don't know where you are looking to do perform this action because it may not be fast (such as if it's being called in a table cell it may be choppy) based upon the string size.
Code:
+ (NSArray *)getNumbersFromString:(NSString *)str {
NSMutableArray *retVal = [NSMutableArray array];
NSCharacterSet *numericSet = [NSCharacterSet decimalDigitCharacterSet];
NSString *placeholder = #"";
unichar currentChar;
for (int i = [str length] - 1; i >= 0; i--) {
currentChar = [str characterAtIndex:i];
if ([numericSet characterIsMember:currentChar]) {
placeholder = [placeholder stringByAppendingString:
[NSString stringWithCharacters:&currentChar
length:[placeholder length]+1];
} else {
if ([placeholder length] > 0) [retVal addObject:[placeholder intValue]];
else placeholder = #"";
return [retVal copy];
}
To explain what is happening above, essentially I am,
going through every character until I find a number
adding that number including any numbers after to a string
once it finds a number it adds it to an array
Hope this helps please ask for clarification if needed

find numbers in text file objective-c [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to generate all of the numbers of pi in Objective-C
I want to implement "am i in pi" for searching birth date in pi numbers,
I have 1 million series of pi Numbers in .txt file, would you please give me some hints for implement this game?
what is the best way? how can I found my birth date in text file?
Thanks in advance
NSString* str = [NSString stringWithContentsOfFile: #"path to your file" encoding: NSASCIIStringEncoding error: nil];
NSRange rng = [str rangeOfString: #"1989"]; //here is the range of the birth year 1989
1 megabyte is sufficiently small that loading and then scanning it is reasonably straightforward. If you wanted to be a little clever, you could map the file into memory and then scan it through the map (avoiding the need to load the entire file into memory, which becomes more important for multi-hundred-MB files).
NSDataReadingOptions options = NSDataReadingMappedIfSafe | NSDataReadingUncached;
NSData *data = [NSData dataWithContentsOfFile:filename
options:options
error:nil];
NSString *string = [[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding];
NSRange range = [string rangeOfString:year];
[string release];
You could add appropriate error handling.
Once I wrote a category of NSString, which has method:
- (NSArray *)occurrencesOfSubstring:(NSString *)string
{
NSMutableArray *result = [NSMutableArray array];
NSRange range = NSMakeRange(0, self.length);
NSUInteger len = self.length;
while (range.location != NSNotFound) {
range = [self rangeOfString:string options:0 range:range];
if (range.location != NSNotFound) {
NSRange resRange = range;
[result addObject:[NSValue valueWithRange:resRange]];
range = NSMakeRange(NSMaxRange(resRange), len - NSMaxRange(resRange));
}
}
return result;
}
It returns array of ranges of searched substring. Hope it helps.

What is Objective C Equivalent for String.indexOf(String, startIndex)

I have search for this but could not found in Apple documentation
You probably want - (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange. The range argument is an NSRange indicating where in the haystack to look for the needle. Passing NSMakeRange(startIndex, [haystack length]-startIndex) should do what you want.
NSRange range = [string rangeOfString:searchString
options:0
range:NSMakeRange(startIndex, [string length]-startIndex)];
if (range.length != 0) {
NSString* resultString = [string substringWithRange:range];
}
You mean you couldn't find this documentation page by searching NSString and clicking the first link?
NSString *substring = [string substringFromIndex:startIndex];

Getting the last word of an NSString

As the title suggests, I would like to get the last word out of an NSString.
I thought using this code:
NSArray *listItems = [someNSStringHere componentsSeparatedByString:#" "];
NSString *lastWordString = [NSString stringWithFormat:#"%#", listItems.lastObject];
anotherNSStringHere = lastWordString;
But I think the NSArray will take a time to load if it's big (and it is big), and it wouldn't recognize a word separated by a comma.
Thanks for helping!
If you want to be super-robust:
__block NSString *lastWord = nil;
[someNSStringHere enumerateSubstringsInRange:NSMakeRange(0, [someNSStringHere length]) options:NSStringEnumerationByWords | NSStringEnumerationReverse usingBlock:^(NSString *substring, NSRange subrange, NSRange enclosingRange, BOOL *stop) {
lastWord = substring;
*stop = YES;
}];
(This should also work with non-Roman languages; iOS 4+/OS X 10.6+.)
Basic explanation:
-enumerateSubstringsInRage:options:usingBlock: does what it says on the tin: it enumerates substrings, which are defined by what you pass in as the options. NSStringEnumerationByWords says "I want words given to me", and NSStringEnumerationReverse says "start at the end of the string instead of the beginning".
Since we're starting from the end, the first word given to us in substring will be the last word in the string, so we set lastWord to that, and then set the BOOL pointed to by stop to YES, so the enumeration stops right away.
lastWord is of course defined as __block so we can set it inside the block and see it outside, and it's initialized to nil so if the string has no words (e.g., if it's empty or is all punctuation) we don't crash when we try to use lastWord.
Give this a try:
NSRange range = [someNSStringHere rangeOfString:#" " options:NSBackwardsSearch];
NSString *result = [someNSStringHere substringFromIndex:range.location+1];
If you wanted to use a regular expression (which can be useful if you want to start getting more complicated in terms of what you're looking for at the end of your string), you could do something like:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\S+\\Z" options:0 error:nil];
NSTextCheckingResult *found = [regex firstMatchInString:inputString options:0 range:NSMakeRange(0, [inputString length])];
if (found.range.location != NSNotFound)
result = [inputString substringWithRange:found.range];
That works great as it also recognizes symbols like # and # which enumerateSubstringsInRange: doesn't do.
NSCharacterSet *charSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *components = [someString componentsSeparatedByCharactersInSet:charSet];
NSString *lastWord = components.lastObject;
The most efficient way is likely to start at the end of the string, examine each character to see if it's part of what you define as a word, and then extract the word you want using substringFromIndex: or substringWithRange:.
You can read symbols from the end of the your string and copy them at the 0 index to result string. Whether you read space or comma, result string wil contain the last word
You could use NSString's function rangeOfSubstring:options: to determine it. For example:
Search the string for a space, using a backwards search option to start the search from the end of the string.
NSRange r = [string rangeOfString:#" " options:NSBackwardsSearch];
This will find the location of the last word of the string. Now just get the string using substringWithRange: For Example:
NSRange found = NSMakeRange(NSMaxRange(r), string.length - NSMaxRange(r));
NSString *foundString = [string substringWithRange:found];
Where r is the range from earlier.
Also be careful to make sure that you check r actually exists. If there is only 1 word in the string, then r will be {NSNotFound, 0}
Hope I could help!
Ben

Getting index of a character in NSString with offset & using substring in Objective-C

I have a string!
NSString *myString=[NSString stringWithFormat:#"This is my lovely string"];
What I want to do is:
Assuming the first character in the string is at index 0. Go to the 11th character (That is 'l' in the above case), and find the position of first occurring space backwards (In the above string, the position of first occurring space if we go backwards from 'l' is at position 10). Let's call the index of this space 'leSpace' having value 10.
Substring the remaining string to a new string using ...
[myString substringFromIndex:leSpace]
...I hope I have explained well. Please help, can you write a snippet or something to help me do this task?
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange
For the options use: NSBackwardsSearch
NSRange range = [myString rangeOfString:#" " options:NSBackwardsSearch range:NSMakeRange(0, 11)];
Example:
NSString *myString=[NSString stringWithFormat:#"This is my lovely string"];
NSRange range = [myString rangeOfString:#" " options:NSBackwardsSearch range:NSMakeRange(0, 11)];
NSLog(#"range.location: %lu", range.location);
NSString *substring = [myString substringFromIndex:range.location+1];
NSLog(#"substring: '%#'", substring);
NSLog output:
range.location: 10
substring: 'lovely string'
Of course there should be error checking that range.location does not equal NSNotFound