Add backslash to String in Objective-c - iphone

I have a problem identical to this problem here.
I even want to encode the same infromation as him (it's a date/time for asp.net)...
When ever I try to add a backslash i get two backslashes since I used \.
Everyone in the thread above has claimed that this is a problem with NSLog and that NSString does treat \\ as a \. I have checked this further by using a packet sniffer to examine the packets I'm sending to the webserver and I can confirm that it is transmitting a double backslash instead of a single backslash.
Does anyone know how to add a backslash to a NSString?

The strings and NSLog are working fine for me:
NSLog(#"\\"); // output is one backslash
NSLog(#"\\\\"); // output is two backslashes
NSLog(#"\\/Date(100034234)\\/"); // output is \/Date(100034234)\/
What am I missing?

Try this:
yourStr = [yourStr stringByReplacingOccurrencesOfString:#"\\\\" withString:#"\\"];
NSLog(#"%#", yourStr);
I had the same problem, turned out that my JSON Parser replaced all occurrances of "\\" with "\\\\", so when I NSLogged my original code like this:
NSString *jsonString = [myJSONStuff JSONRepresentation];
NSLog(#"%#", jsonString);
This is what I got:
{TimeStamp : "\\/Date(12345678)\\/"}
However, the string itself contained FOUR backslashes (but only 2 of them are printed by NSLog).
This is what helped me:
NSString *jsonString = [myJSONStuff JSONRepresentation];
jsonString = [jsonString stringByReplacingOccurrencesOfString:#"\\\\" withString:#"\\"];
NSLog(#"%#", jsonString);
The result:
{TimeStamp : "\/Date(12345678)\/"}

Related

Convert or Print CGPDFStringRef string

How to convert a CGPDFStringRef to unicode char? I have used CGPDFStringCopyTextString to get the string and then [string characterAtIndex:i] to cast to unichar, is this the right way? or is there any way to get the bytes of the string and convert to unicode directly?
Need some guidance here.
NSString is capable of handling of unicode characters itself, you just need to convert the CGPDFString to NSString and further you can use it as follows:
NSString *tempStr = (NSString *)CGPDFStringCopyTextString(objectString);
although UPT's answer is correct, it will produce a memory leak
from the documentation:
CGPDFStringCopyTextString
"...You are responsible for releasing this object."
the correct way to do this would be:
CFStringRef _res = CGPDFStringCopyTextString(pdfString);
NSString *result = [NSString stringWithString:(__bridge NSString *)_res];
CFRelease(_res);
It's not a bad idea, even if you can access the CGPDFString directly using CGPDFStringGetBytePtr. You will also need CGPDFStringGetLength to get the string length, as it may not be null-terminated.
See the documentation for more info

Different kind of UTF8 decoding in NSString

I have searched a lot about UTF8 decoding, but not found the answer yet.
I receive an UTF-8 decode NSString from my NSXMLParser:
NSString *tempString = #"Test message readability is óké";
In someway I can't find the way to change this encoded text to:
Test message readability is óké
I could tell all the options I tried but I don't think that should be necessary. Could please some help?
Thnx!
The NSXMLParser will treat the text using the character encoding that the XML specifies. I believe in your case the XML do not specify UTF-8 explicitly.
The text seems to be ISO Latin 1. If you can not do anything about the server generating the XML then you can apply this hack:
char* tempString = [string cStringUsingEncoding:NSISOLatin1StringEncoding];
string = [NSString stringWithUTF8String:tempString];
I have verified that this works by testing this from the GDB prompt:
po [NSString stringWithUTF8String:(char*)[#"Test message readability is óké" cStringUsingEncoding:5]]
You're doing it wrong. What you want is:
char *s = "Test message readability is óké";
//Note: this is a one-byte-character C string, not an NSString!
NSString *tempString = [NSString stringWithCString:s encoding:NSUTF8StringEncoding];
Also keep in mind that when you initialize string constants, what actually goes to program memory depends on the encoding of the current file. If it's already UTF-8, then the characters will be doubly-encoded - you'll get characters Ã,³, etc. encoded as UTF8 in the C string.
In other words, using a string constant is probably a wrong move to begin with. Please give more context to the problem.
Standart encoding and decoding like this:
For encoding:
NSString *content = [bodyTextView.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
For decoding:
NSString *decodedString = [msg.content stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

How can I remove quotes from an NSString?

I am trying to remove quotes from something like:
"Hello"
so that the string is just:
Hello
Check out Apple's docs:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/
You probably want:
stringByReplacingOccurrencesOfString:withString:
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
So, something like this should work:
newString = [myString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
I only wanted to remove the first quote and the last quote, not the quotes within the string so here's what I did:
challengeKey = #"\"I want to \"remove\" the quotes.\"";
challengeKey = [challengeKey substringFromIndex:1];
challengeKey = [challengeKey substringToIndex:[challengeKey length] - 1];
Hope this helps others looking for the same thing. NSLog and you'll get this output:
I want to "remove" the quotes.

NSString returning jibberish

Totally lost with this one. Here's my code:
theColor = [NSString stringWithFormat:#"white"];
NSLog(#"%s", theColor);
Which is returing:
†t†å
I must be doing something stupid, but can not figure it out for the life of me.
Change your print to:
NSLog(#"%#", theColor);
Hope it helps.
The thing is that %s expects a C-string (char array with a NULL terminator) and you are passing a NSString instance which is not the same as a C-string. The modifier you need in a format to print NSString content is %#.
%s is for printing C-style strings.
%# is for printing Objective-C objects (like NSString).
BTW: “theColor = [NSString stringWithFormat:#"white"];” – why not “theColor = #"white";”?
Greetings

RegExKitLite Expression Question

I'm having trouble coming up with an RegExKitLite expression that will match. I'm parsing a string and I want it to grab everything till it comes upon the first occurrence of a colon
What would be the expression in RegExKitLite to do that?
Thanks!
This regex will match everything from the start until (but excluding) the first colon:
^[^:]*
To include the first colon is as simple as putting it on the end:
^[^:]*:
So, to use either of those with RegexKitLite, you can do:
NSString * firstItem = [someString stringByMatching:#"^[^:]*" capture:0];
Note how there is no parentheses - since * is greedy you can simply use the negated class and use captured group 0 (i.e. the whole match).
It's worth noting that most languages will include functions that allow you to do this with a regular function, for example ListFirst(MyString,':') or MyString.split(':')[0]
I suspect Objective-C has something similar to this ... yep, see here
NSString *string = #"oop:ack:bork:greeble:ponies";
NSArray *chunks = [string componentsSeparatedByString: #":"];
To do this specifically with RegexKitLite, you'll need to do the following:
Add the RegexKitLite.h/.m files to your project
Import RegexKitLite.h into the file where you need to use regular expressions
Use the following to grab the stuff before the colon:
NSString * everythingBeforeTheColon = [someString stringByMatching:#"([^:]*):" capture:1];
I just updated my SO answer here, so I figured I'd use that to benchmark the standard foundation componentsSeparatedByString: and RegexKitLites componentsSeparatedByRegex:. The line of code inside the for() loop for each was (essentially):
NSString *string = #"oop:ack:bork:greeble:ponies";
for() { NSArray *chunks = [string componentsSeparatedByString: #":"]; }
for() { NSArray *chunks = [string componentsSeparatedByRegex: #":"]; }
Times returned were (time is in microseconds per operation):
componentsSeparatedByString: 3.96810us
componentsSeparatedByRegex: 2.46155us
EDIT:
I thought I'd go one better: How to use RegexKitLite to create a NSArray of NSArrays from a string containing multiple lines of colon separated data (ie, /etc/passwd). Modified from the comma separated value example in the RegexKitLite documentation. When finished, the variable splitLinesArray contains the finished product.
NSString *theString = #"a:b:c\n1:2:3\nX:Y:Z\n"; // An example string to work on.
NSArray *linesArray = [theString componentsSeparatedByRegex:#"(?:\r\n|[\n\v\f\r\\x85\\p{Zl}\\p{Zp}])"];
id splitLines[[linesArray count]];
NSUInteger splitLinesIndex = 0UL;
for(NSString *lineString in linesArray) { splitLines[splitLinesIndex++] = [lineString componentsSeparatedByRegex:#":"]; }
NSArray *splitLinesArray = [NSArray arrayWithObjects:splitLines count:splitLinesIndex];