How to replace single slash "\" to "\\\" in Objective-C - ios

I'm trying to replace single slash to triple slash in Objective-C. I'm unable to do conversion.
Example:
NSString *string = "pW`-={}|[]456\";
string = [string stringByReplacingOccurrencesOfString:#"\\\" withString:#"\"];
I want to output: pW`-={}|[]456\\

Every back-slash in Objective-C string literal should be presented with two back-slashes (first one is escaping back-slash), otherwise it will not even compile, so
If you want convert this
pW`-={}|[]456\
into this
pW`-={}|[]456\\\
it needs to call
string = [string stringByReplacingOccurrencesOfString:#"\\" withString:#"\\\\\\"];
if vice-versa, then correspondingly
string = [string stringByReplacingOccurrencesOfString:#"\\\\\\" withString:#"\\"];

Related

Objective C: Replace double backslash with a single backslash

I'm trying to replace a string that holds double backslash to a string with only single backslash, for example:
\\This\\Is\\Not\\Working
To:
\This\Is\Not\Working
Using:
str = [str stringByReplacingOccurrencesOfString:#"\\\\" withString#"\\"];
But for some reason, The string remains the same (with the double backslash) every single time. What am i doing wrong here?
Sadly, I misinterpreted the console log output. the string was fine, the debugger just showed the single slash as a doubled one. (For escaping purposes i'd imagine).
The below lines of code is fine:
NSString *str=#"\\This\\Is\\Not\\Working";
str = [str stringByReplacingOccurrencesOfString:#"\\\\" withString#"\\"];
Just check value by NSLog or by printing, because in debug console slash is represented as double slash.
Check image for more clear understanding:
NSString *Str = #"\\This\\Is\\Not\\Working";
NSLog(#"%#",Str);// print:-\This\Is\Not\Working
Str = [Str stringByReplacingOccurrencesOfString:#"\\\\" withString:#"\\"];// in this no replace occurres
NSLog(#"%#",Str); // print:-\This\Is\Not\Working
NSString *Str1 = #"\\\\This\\\\Is\\\\Not\\\\Working";
NSLog(#"%#",Str1);// print:-\\This\\Is\\Not\\Working
Str1 = [Str1 stringByReplacingOccurrencesOfString:#"\\\\" withString:#"\\"];
NSLog(#"%#",Str1);// print:-\This\Is\Not\Working
Try this:
NSString *str = #"\\This\\Is\\Not\\Working";
str = [str stringByReplacingOccurrencesOfString:#"\\" withString:#"\\\\"];
NSLog(#"%#", [str stringByReplacingOccurrencesOfString:#"\\\\" withString:#"\\"]);
1st Line is your user input.
2nd Line converts the double back-slashed user input string into four back-slashed string
3rd line simply replaces four back slashes with two back slashes which results in printing single back slash

remove string between parentheses [iOS]

i have a NSString with parentheses in it.
I would like to remove the Text inside of the parentheses.
How to do that? ( In Objective-C )
Example String:
Tach auch. (lockeres Ruhrdeutsch) Und Hallo!
I would like to Remove "(lockeres Ruhrdeutsch)" from the String,
but the Strings i have to edit are always different.
How can i remove the String betweeen "(" and ")"?
Best Regards
Use regular expression:
NSString *string = #"Tach auch. (lockeres Ruhrdeutsch) Und Hallo!";
NSString *filteredString = [string stringByReplacingOccurrencesOfString:#"\\(.*\\)"
withString:#""
options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
NSLog(#"%#", filteredString);
If you want to consider also a whitespace character after the closing parenthesis, add \\s? to the end of the regex pattern.
Here is the function you can call to get your required string:
-(NSString*)getStringWithBlankParaFrom:(NSString*)oldStr{
NSArray*strArray1=[oldStr componentsSeparatedByString:#"("];
NSString*str2=[strArray1 objectAtIndex:1];
NSArray*strArray2 =[str2 componentsSeparatedByString:#")"];
NSString*strToReplace=[strArray2 objectAtIndex:0];
return [oldStr stringByReplacingOccurrencesOfString:strToReplace withString:#""];
}
This function is valid for the string which contains one pair of parentheses**()**
You can change it as per your requirement.
Hope this helps!

Xcode - UTF-8 String Encoding

I have a strange problem encoding my String
For example:
NSString *str = #"\u0e09\u0e31\u0e19\u0e23\u0e31\u0e01\u0e04\u0e38\u0e13";
NSString *utf = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog("utf: %#", utf);
This worked perfectly in log
utf: ฉันรักคุณ
But, when I try using my string that I parsed from JSON with the same string:
//str is string parse from JSON
NSString *str = [spaces stringByReplacingOccurrencesOfString:#"U" withString:#"u"];
NSLog("str: %#, str);
NSString *utf = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog("utf: %#", utf);
This didn't work in log
str: \u0e09\u0e31\u0e19\u0e23\u0e31\u0e01\u0e04\u0e38\u0e13
utf: \u0e09\u0e31\u0e19\u0e23\u0e31\u0e01\u0e04\u0e38\u0e13
I have been finding the answer for hours but still have no clue
Any would be very much appreciated! Thanks!
The string returned by JSON is actually different - it contains escaped backslashes (for each "\" you see when printing out the JSON string, what it actually contains is #"\").
In contrast, your manually created string already consists of "ฉันรักคุณ" from the beginning. You do not insert backslash characters - instead, #"\u0e09" (et. al.) is a single code point.
You could replace this line
NSString *utf = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
with this line
NSString *utf = str;
and your example output would not change. The stringByReplacingPercentEscapesUsingEncoding: refers to a different kind of escaping. See here about percent encoding.
What you need to actually do, is parse the string for string representations of unicode code points. Here is a link to one potential solution: Using Objective C/Cocoa to unescape unicode characters. However, I would advise you to check out the JSON library you are using (if you are using one) - it's likely that they provide some way to handle this for you transparently. E.g. JSONkit does.

NSString separation-iOS

I have following strings. But I need to separate them by this "jsonp1343930692" and assign them NSString again. How could I that? I could able to separate them to NSArray but I don't know how to separate to NSString.
jsonp1343930692("snapshot":[{"timestamp":1349143800,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448}]}]})
jsonp1343930692("snapshot":[{"timestamp":1349144700,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448,"attr":{"ozone_level":57,"exp":"IN","gridpoint":"30.17:-95.5"}},{"label_id":10,"lat":29.036944,"lng":-95.438333}]}]})
The jsonp1343930692 prefix in your string is odd: I don't know where you string come from, but it really seems to be some JSON string with this strange prefix that has no reason to be there. The best shot here is probably to check if it is normal to have this prefix, for example if you get this string from a WebService it is probably the WebService fault to return this odd prefix.
Anyway, if you want to remove the jsonp1343930692 prefix of your string, you have multiple options:
Check that the prefix is existant, and if so, remove the right number of characters from the original string:
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
if ([str hasPrefix:kStringToRemove])
{
// rebuilt a string by only using the substring after the prefix
str = [str substringFromIndex:kStringToRemove.length];
}
Split your string in multiple parts, using the jsonp1343930692 string as a separator
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
NSArray* parts = [str componentsSeparatedByString:kStringToRemove];
str = [parts componentsJoinedByString:#""];
Replace every occurrences of jsonp1343930692 by the empty string.
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
str = [str stringByReplacingOccurrencesOfString:kStringToRemove withString:#""];
So in short you have many possibilities depending on what exactly you want to do :)
Of course, once you have removed your strange jsonp1343930692 prefix, you can deserialize your JSON string to obtain a JSON object (either using some third-party lib like SBJSON or using NSJSONSerializer on iOS5 and later, etc)
Have a look at the NSJSONSerialization class to turn this into a Cocoa collection that you can deal with.

Objective-C - Remove last character from string

In Objective-C for iOS, how would I remove the last character of a string using a button action?
In your controller class, create an action method you will hook the button up to in Interface Builder. Inside that method you can trim your string like this:
if ([string length] > 0) {
string = [string substringToIndex:[string length] - 1];
} else {
//no characters to delete... attempting to do so will result in a crash
}
If you want a fancy way of doing this in just one line of code you could write it as:
string = [string substringToIndex:string.length-(string.length>0)];
*Explanation of fancy one-line code snippet:
If there is a character to delete (i.e. the length of the string is greater than 0)
     (string.length>0) returns 1 thus making the code return:
          string = [string substringToIndex:string.length-1];
If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
     (string.length>0) returns 0 thus making the code return:
          string = [string substringToIndex:string.length-0];
     Which prevents crashes.
If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:
[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];
The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.
In fact, the iOS header file which contains the declaration of substringToIndex contains the following comment:
Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters
See how to use rangeOfComposedCharacterSequenceAtIndex: to delete the last character correctly.
The documentation is your friend, NSString supports a call substringWithRange that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString it is immutable. If you have an NSMutableString is has a method called deleteCharactersInRange that can modify the string in place
...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...

Resources