Objective C - NSRange and rangeOfString - objective-c

I have a little problem with NSRange and rangeOfString. I want to search a substring in a given string which is working fine, but only to find a exact string and theres the problem i need to find a substring which begins always the same and ends always the same. I tried it already with something like that:
match = [strIn rangeOfString: #"truni/begin/*/end"];
But thats not working. So i need a way to to do this. Here is the specific part of the Code in full:
NSRange match;
match = [strIn rangeOfString: #"turni/begin/sHjeUUej/end"];
NSRange range = NSMakeRange(match.location, match.length);
NSString *strOut = [strIN substringWithRange:range];
You see the string "turni/begin/sHjeUUej/end" will always be the same except for the part "sHjeUUej". Hope someone can help me.
Thanks in advance.

Use a regular expression with:
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
with an option of RegularExpressionSearch.
See ICU User Guide Regular Expressions for information on creating regular expressions.

you can use prefix/suffix
if ([strIn hasPrefix:#"truni/begin/"] && [strIn hasSuffix:#"end"]) {
//match

You can use a simpler solution if you make sure that your string always starts with turni/begin/ and ends with /end.
You can use:
NSString *strOut = [[strIn stringByReplacingOccurrencesOfString:#"turni/begin/" withString:#""] stringByReplacingOccurrencesOfString:#"/end" withString:#""];
With that, you can retrieve the string between the two others with only one line of code and less comparations.

Related

CoreData NSPredicate MATCHES regex

I have a CoreData table with a field holding a string of a series of numbers separated by commas. I want to be able to run a fetch with a predicate that will match against a given specific number.
For example if fieldName = "12,52,66,89,2,8"
And I want to search for 2, then it should match the second to last number in the string and include that record in the results.
Using the regular expression:
^2|,2,|,2
I have found it working satisfactorily for my test cases, testing it using this site for example: https://www.regexpal.com/
However, when I pass this into an NSPredicate for a NSFetchRequest, I can't get it to match
NSNumber *val = #2;
NSString *regex = [NSString stringWithFormat:#"^%#|,%#,|,%#", val, val, val];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"fieldName MATCHES %#", regex];
Replacing the MATCHES with a CONTAINS val makes it work, but of course it will also incorrectly match any occurrence of the digits.
I suspect I am missing something stupid about formatting for CoreData (or regex), but I've tried many variations, and I'm hoping a kind soul reading this will put me out of my misery :)
Disclaimer: I haven't used Objective C. This answer is based on my regex knowledge and some documentation.
MATCHES
The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions).
That sounds like how Java uses the method "matches" in which case "^2|,2,|,2" can never match the entire string. This differs from regexpal which will always search the text. The regex you would need is more like
.*\b2\b.*
(the ^$ are assumed in Java). Another option is to split the string.

Required character in NSString is replaced with encoded variable

I have an NSString that contains a value "\U2212" instead of "-" which is coming from API. When I tried to replace this string with needed character using subString occurrence method it shown error. So how do I replace my NSString that contains "\U2212" with "-". I tried the following code. Please help me. I searched many things but nothing helped. Thanks in advance.
input:"(UTC\U221206:00) Canada/Central"
Desired output:"(UTC-06:00) Canada/Central"
code:
NSString *timezoneDisplayValue = [timezone valueForKey:#"tomeZoneDisplayValue"];
timezoneDisplayValue = [timezoneDisplayValue stringByReplacingOccurrencesOfString:#"\U2212" withString:#"-"];
below code returns YES or NO, whether your string has any encoding...
[apiString canBeConvertedToEncoding:NSASCIIStringEncoding];
If NO is returned, then convert with the correct encoding type :
[apiString dataUsingEncoding:NSUTF16BigEndianStringEncoding];

Replacing a single occurrence of string Obj-c

I am trying to replace only one of the occurrences of a NSString with another string. I know that you can use stringByReplacing*Occurrences*OfString; however, that replaces all occurrences. What I am looking for is more like stringByReplacing*Occurrence*OfString. If anyone could help me that would be great. Thanks,
Jnani
Something like this?
NSRange location = [someString rangeOfString:stringToReplace];
NSString* result = [someString stringByReplacingCharactersInRange:location withString:stringToReplaceWith];

Reading String from File with Objective C

This one is weird. Hopefully I will ask the right question:
I'm using an md5 method to create a checksum value which I then write to a file. Then afterwards I read the file using this:
NSString * id_From_File = [[NSString alloc]
initWithContentsOfFile:path_to_ID
encoding:NSUTF8StringEncoding
error:&error];
The result gets placed in a NSString which when I print gives me very strange behaviour. For example when I use this to print,
id_with_date = [NSString stringWithFormat:#" %# %#", dateString, id_From_File];
it will print both strings if dateString is placed in the first parameter and id_From_File in the second. If I switch them around (which I need to do) only id_From_File shows.
Edit 1: Example of the switch:
id_with_date = [NSString stringWithFormat:#" %# %#", id_From_File, dateString];
I strongly believe this has something to do with the encoding of the id_From_File string.
Any knowledge!?
Thanks,
NSString should actually be capable of recognizing null characters as the file ending. Did you try to use a different method to load the string. I'd go for this one instead:
- (id)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
This method automatically detects the file's encoding instead of decoding it with a fixed one.
I've solved the problem!
It has to do with the fact that some strings use a null character to identify the end. Allow me to explain:
Lets say you have two strings, one with a null character at the end and one that doesn't. Depending on which way you order them, they will be read differently when concatenated.
"somestring(null char)" + "another string"
The above, in some code, will read
somestring
if places are switched
"another string" + "somestring(null char)"
then you get
"another string somestring"
My simple hack to fix this was to make a new string with a substring of "some string" which easily got rid of that last char that was causing the bug.
I hope this is clear and helpful!

How to find out if there is an "." in an NSString?

Have got an
NSString *str = #"12345.6789"
and want to find out if there is that "." character inside of it. I'm afraid that there are ugly char-encoding issues when I would just try to match an #"." against this? How would you do it to make sure it always finds a match if there is one?
I just need to know that there is a dot in there. Everything else doesn't matter.
You can use rangeOfString: message to get the range where your "." is.
The prototype is:
- (NSRange)rangeOfString:(NSString *)aString
You can find more info about this message in: Mac Dev Center
There would be something like this:
NSRange range;
range = [yourstring rangeOfString:#"."];
NSLog(#"Position:%d", range.location);
If you need to, there is another message ( rangeOfString:options: ) where you can add some options like "Case sensitive" and so on.
If [str rangeOfString:#"."] returns anything else than {NSNotFound, 0}, the search string was found in the receiver. There are no encoding issues as NSString takes care of encoding. However, there might be issues if your str is user-provided and could contain a different decimal separator (e.g., a comma). But then, if str really comes from the user, many other things could go wrong with that comparison anyway.
To check . symbol, it will be useful.
if ([[str componentsSeparatedByString:#"."] count]>1) {
NSLog(#"dot is there");
}else{
NSLog(#"dot is not there");
}
If what you really want to do is determine whether the string represents a number with a fractional part, a better solution is to feed the string to a number formatter, then examine the number's doubleValue to see whether it has a fractional part.
For the latter step, one way would be to use the modf function, which returns both the fractional part (directly) and the integral part (by reference). If the fractional part is greater than zero (or some appropriately small fraction below which you're willing to tolerate), then the number has a fractional part.
The reason why this is better is because not everybody writes decimal fractions in the “12345.6789” format. Some countries use a comma instead, and I'm sure that's not the only variation. Let the number formatter handle such cases for you.
I wrote a little method to make things a little more natural if you use this sort of thing a whole bunch in your project:
+(BOOL)seeIfString:(NSString*)thisString ContainsThis:(NSString*)containsThis
{
NSRange textRange = [[thisString lowercaseString] rangeOfString:[containsThis lowercaseString]];
if(textRange.location != NSNotFound)
return YES;
return NO;
}
Enjoy!