How can we write " in nsstring? - iphone

I have to initialize string as "Rose" including Quotation Mark. How to write " in our string?

Escape the double quote with \
NSString *yourString = #"\"Rose\"";

Use the escape character: \
NSString *r = #"\"Rose\"";
You can find additional information about Escape character and String literal.

Escape it with a backslash:
#"\"Rose\""

Escape the quotation marks.
Example:
NSString *str = #"\"Rose\"";

NSString *yourString = #"\"Rose\"";

In swift 5, you can write with a hashtag :
let raw = #"You can create "raw" strings in Swift 5."#
Output :
You can create "raw" strings in Swift 5.

Related

how to remove \ from a word \"hello\" in objective c?

From webservice i get the data as json but the problem is the json comes with all " with a \ ie "all" comes as \"all\"
How to make this a valid json and then a dictionary?
{
GetDataResult = "[{\"www\":{\"0\":{\"ID\":\"10233\",\"Queue\":\"COMPLETED\",\"EstCommName\":\"\U062e\U0631\U0645 \U0644\U0644\U0627\U0644\U0648\U0645\U0646\U064a\U0648\U0645 \U0648\U0627\U0644\U0632\U062c\U0627\U062c\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"},\"1\":{\"ID\":\"10304\",\"Queue\":\"COMPLETED\",\"EstCommName\":\"\U0627\U062d\U0645\U062f \U0627\U0644\U0643\U0646\U062f\U064a \U0644\U0644\U0627\U0644\U0645\U0648\U0646\U064a\U0648\U0645 \U0648\U0627\U0644\U0632\U062c\U0627\U062c\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"},\"2\":{\"ID\":\"10667\",\"Queue\":\"FRESH\",\"EstCommName\":\"\U0645\U0646\U062c\U0631\U0629 \U0627\U0644\U062e\U0632\U0646\U0629\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"},\"3\":{\"ID\":\"10777\",\"Queue\":\"FRESH\",\"EstCommName\":\"\U0645\U0624\U0633\U0633\U0647 \U062c\U0647\U0627\U0645 \U0644\U0627\U0639\U0645\U0627\U0644 \U0627\U0644\U0633\U064a\U0631\U0627\U0645\U064a\U0643\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"}}},{\"asd\":{}},{\"ssd\":{}}]";
In other words
TLDR
how to remove \ from a word \"hello\".? ie output needed is "hello".
What i tried
NSLog(#"%#",[[op objectForKey:#"GetSampleDataResult"] stringByReplacingOccurrencesOfString:#"\"" withString:#""]);
I have not tried this but something like this can work for you.
Sample Code :
NSString *yourString = [yourJSON objectForKey:#"GetDataResult"];
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *www = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"www :: %#",www);
I tried like this below:--
NSString *word= #"'\'hello'\'";
NSArray *arr=[word componentsSeparatedByString:#"'\'"];
for (NSString *str in arr)
{
if ([str length] >0)
{
NSLog(#"%#",str);
}
}
from the top of my head, to replace \" you need to specify it as \\\"
reason being that \ itself is used as an escape character and thus you need to escape:
\ with \\
" with \"
but the quotes are needed so you need to rid yourself of the \
so this:
NSLog(#"%#",[[op objectForKey:#"GetSampleDataResult"]
stringByReplacingOccurrencesOfString:#"\\"
withString:#""]);
but as mentioned, NSJSONSerialization is the best way to go about this
[string stringByReplacingOccurrencesOfString:#"\\\"" withString:#"\""];
Be careful with quotation marks and backslashes.
Result of \\\" will be \", exactly what you need to find.
Result of \" will be ", exactly what you need to replace.
Edit: This is answer to “How to remove \ from a word \"hello\"?”, not a solution to the problem.

Decode URL into JSON

I am getting the following response
param=%7B%22paymentMode%22:%22%22,%22transactionId%22:%2231674%22,%22pgRespCode%22:%223%22,%22TxMsg%22:%22Canceled%20by%20user%22,%22authIdCode%22:%22%22,%22currency%22:%22INR%22,%22amount%22:%221.00%22,%22addressStreet1%22:%22Sesame%20street%22,%22addressStreet2%22:%22%22,%22isCOD%22:%22%22,%22loadStatus%22:%22fail%22,%22TxId%22:%22123456%22,%22addressCountry%22:%22India%22,%22firstName%22:%22Ankur%22,%22TxGateway%22:%22%22,%22signature%22:%2245558eb93513aa7a4f2fba24e0ba577b26eb5f40%22,%22addressState%22:%22Pune%22,%22lastName%22:%22Arya%22,%22addressCity%22:%22%22,%22TxRefNo%22:%22CTX1307151506338704178%22,%22loadAmount%22:%221.00%20INR%22,%22pgTxnNo%22:%22CTX1307151506338704178%22,%22TxStatus%22:%22CANCELED%22,%22email%22:%22daredevil.suyash#gmail.com%22,%22issuerRefNo%22:%22%22,%22mobileNo%22:%229900414420%22,%22addressZip%22:%22411045%22%7D
how can I decode it into the following
param={"paymentMode":"","transactionId":"31674","pgRespCode":"3","TxMsg":"Canceled by user","authIdCode":"","currency":"INR","amount":"1.00","addressStreet1":"Sesame street","addressStreet2":"","isCOD":"","loadStatus":"fail","TxId":"123456","addressCountry":"India","firstName":"Ankur","TxGateway":"","signature":"45558eb93513aa7a4f2fba24e0ba577b26eb5f40","addressState":"Pune","lastName":"Arya","addressCity":"","TxRefNo":"CTX1307151506338704178","loadAmount":"1.00 INR","pgTxnNo":"CTX1307151506338704178","TxStatus":"CANCELED","email":"daredevil.suyash#gmail.com","issuerRefNo":"","mobileNo":"9900414420","addressZip":"411045"}
You can try this method stringByReplacingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy]
Taken from this question urldecode in objective-c
//
NSString *param=#"%7B%22paymentMode%22:%22%22,%22transactionId%22:%2231674%22,%22pgRespCode%22:%223%22,%22TxMsg%22:%22Canceled%20by%20user%22,%22authIdCode%22:%22%22,%22currency%22:%22INR%22,%22amount%22:%221.00%22,%22addressStreet1%22:%22Sesame%20street%22,%22addressStreet2%22:%22%22,%22isCOD%22:%22%22,%22loadStatus%22:%22fail%22,%22TxId%22:%22123456%22,%22addressCountry%22:%22India%22,%22firstName%22:%22Ankur%22,%22TxGateway%22:%22%22,%22signature%22:%2245558eb93513aa7a4f2fba24e0ba577b26eb5f40%22,%22addressState%22:%22Pune%22,%22lastName%22:%22Arya%22,%22addressCity%22:%22%22,%22TxRefNo%22:%22CTX1307151506338704178%22,%22loadAmount%22:%221.00%20INR%22,%22pgTxnNo%22:%22CTX1307151506338704178%22,%22TxStatus%22:%22CANCELED%22,%22email%22:%22daredevil.suyash#gmail.com%22,%22issuerRefNo%22:%22%22,%22mobileNo%22:%229900414420%22,%22addressZip%22:%22411045%22%7D";
NSString *newParam = [param stringByReplacingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
NSLog(#"%#",newParam);
Do string replacement stuff with that to get it into a more readable form.
string = [string stringByReplacingOccurrencesOfString: #"%%22" withString:#"\""];
string = [string stringByReplacingOccurrencesOfString: #"%%7B" withString:#"{"];
string = [string stringByReplacingOccurrencesOfString: #"%%7D" withString:#"}"];
And so on, until you get it into something you want.
You are basically replacing the unicode representation of the character into the actual readable character

How to replace occurrences of multiple strings with multiple other strings [NSString]

NSString *string = [myString stringByReplacingOccurrencesOfString:#"<wow>" withString:someString];
I have this code. Now suppose my app's user enters two different strings I want to replace with two different other strings, how do I achieve that? I don't care if it uses private APIs, i'm developing for the jailbroken platform. My user is going to either enter or or . I want to replace any occurrences of those strings with their respective to-be-replaced-with strings :)
Thanks in advance :P
Both dasblinkenlight’s and Matthias’s answers will work, but they both result in the creation of a couple of intermediate NSStrings; that’s not really a problem if you’re not doing this operation often, but a better approach would look like this.
NSMutableString *myStringMut = [[myString mutableCopy] autorelease];
[myStringMut replaceOccurrencesOfString:#"a" withString:somethingElse];
[myStringMut replaceOccurrencesOfString:#"b" withString:somethingElseElse];
// etc.
You can then use myStringMut as you would’ve used myString, since NSMutableString is an NSString subclass.
The simplest solution is running stringByReplacingOccurrencesOfString twice:
NSString *string = [[myString
stringByReplacingOccurrencesOfString:#"<wow>" withString:someString1]
stringByReplacingOccurrencesOfString:#"<boo>" withString:someString2];
I would just run the string replacing method again
NSString *string = [myString stringByReplacingOccurrencesOfString:#"foo" withString:#"String 1"];
string = [string stringByReplacingOccurrencesOfString:#"bar" withString:#"String 2"];
This works well for me in Swift 3.1
let str = "hi hello hey"
var replacedStr = (str as NSString).replacingOccurrences(of: "hi", with: "Hi")
replacedStr = (replacedStr as NSString).replacingOccurrences(of: "hello", with: "Hello")
replacedStr = (replacedStr as NSString).replacingOccurrences(of: "hey", with: "Hey")
print(replacedStr) // Hi Hello Hey

regular expression to match " but not \"

How can I construct a regular expression which matches an literal " but only if it is not preceded by the escape slash namely \
I have a NSMutableString str which prints the following on NSLog. The String is received from a server online.
"Hi, check out \"this book \". Its cool"
I want to change it such that it prints the following on NSLog.
Hi, check out "this book ". Its cool
I was originally using replaceOccurencesOfString ""\" with "". But then it will do the following:
Hi, check out \this book \. Its cool
So, I concluded I need the above regular expression to match only " but not \" and then replace only those double quotes.
thanks
mbh
[^\\]\"
[^m] means does not match m
Not sure how this might translate to whatever is supported in the iOS apis, but, if they support anchoring (which I think all regex engines should), you're describing something like
(^|[^\])"
That is, match :
either the beginning of the string ^ or any character that's not
\ followed by:
the " character
If you want to do any sort of replacement, you'll have to grab the first (and only) group in the regex (that is the parenthetically grouped part of the expression) and use it in the replacement. Often this value labeled as $1 or \1 or something like that in your replacement string.
If the regex engine is PCRE based, of course you could put the grouped expression in a lookbehind so you wouldn't need to capture and save the capture in the replacement.
Not sure about regex, a simpler solution is,
NSString *str = #"\"Hi, check out \\\"this book \\\". Its cool\"";
NSLog(#"string before modification = %#", str);
str = [str stringByReplacingOccurrencesOfString:#"\\\"" withString:#"#$%$#"];
str = [str stringByReplacingOccurrencesOfString:#"\"" withString:#""];
str = [str stringByReplacingOccurrencesOfString:#"#$%$#" withString:#"\\\""];//assuming that the chances of having '#$%$#' in your string is zero, or else use more complicated word
NSLog(#"string after modification = %#", str);
Output:
string before modification = "Hi, check out \"this book \". Its cool"
string after modification = Hi, check out \"this book \". Its cool
Regex: [^\"].*[^\"]. which gives, Hi, check out \"this book \". Its cool
It looks like it's a JSON string? Perhaps created using json_encode() in PHP on the server? You should use the proper JSON parser in iOS. Don't use regex as you will run into bugs.
// fetch the data, eg this might return "Hi, check out \"this book \". Its cool"
NSData *data = [NSData dataWithContentsOfURL:#"http://example.com/foobar/"];
// decode the JSON string
NSError *error;
NSString *responseString = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
// check if it worked or not
if (!responseString || ![responseString isKindOfClass:[NSString class]]) {
NSLog(#"failed to decode server response. error: %#", error);
return;
}
// print it out
NSLog(#"decoded response: %#", responseString);
The output will be:
Hi, check out "this book ". Its cool
Note: the JSON decoding API accepts an NSData object, not an NSString object. I'm assuming you also have a data object and are converting it to a string at some point... but if you're not, you can convert NSString to NSData using:
NSString *responseString = [NSJSONSerialization JSONObjectWithData:[myString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
More details about JSON can be found at:
http://www.json.org
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

Localization with variable and constant definition in header file

How do I use NSLocalizedString in this case when I have a header where I define a few parameters, say:
#define appKey #"appKey1 is: %#"
I think I know that my Localizable.strings should look like that:
"blabla" = "appKey1 is: %#"
but how do I use NSLocalizedString? I read that I need to use stringWithFormat, but not sure how...
thanks!
You would define your constant as:
#define appKey NSLocalizedString(#"appKey1 is: %#", #"appkey constant")
Then it should get picked up by the genstrings tool in the usual way.
In the strings file it would then come out like this:
/* appkey constant */
"appKey1 is: %#" = "appKey1 is: %#";
And you would translate just the right hand side.
String literals are acceptable in NSLocalizedStrings. What you need to do is something like
#define appKey NSLocalizedString(BlahBlah , comments);
"BlahBlah" = "appKey1 is: %#";
(Be sure to end your lines with a semi-colon in Localizable.strings, or it will end up being corrupted).
This is how you would do it normally,
NSString * myString = [NSString stringWithFormat:#"appKey1 is: %#",yourAppKeyString];
Since you have it defined you can use it like so
NSString * myString = [NSString stringWithFormat:appKey,yourAppKeyString];
Either case both would fill your myString like so
yourAppKeyString = #"keyString";
myString = #"appKey1 is: keyString";
NSString * myString = [NSString stringWithFormat: NSLocalizedString(#"appKey", #""),yourAppKeyString];