I am working on an iPhone OS application that sends an xml request to a webservice. In order to send the request, the xml is added to an NSString. When doing this I have experienced some trouble with quotation marks " and backslashes \ in the xml file, which have required escaping. Is there a complete list of characters that need to be escaped?
Also, is there an accepted way of doing this escaping (ie replacing \ with \\ and " with \") or is it a case of creating a method myself?
Thanks
NSString *escapedString = [unescapedString stringByReplacingOccurrencesOfString:#"\\" withString:#"\\\\"];
escapedString = [escapedString stringByReplacingOccurrencesOfString:#"\"" withString:#"\\\""];
Doesn't fully answer your question, but seems like it might help with the second part...
You can use a NSScanner that will scan for characters from a character set and if found, it will add the escaping \\ to a new string and copy the next substring from the found special character till the next.
NSString *sourceString = /* Some input String*/;
NSMutableString *destString = [#"" mutableCopy];
NSCharacterSet *escapeCharsSet = [NSCharacterSet characterSetWithCharactersInString:#" ()\\"];
NSScanner *scanner = [NSScanner scannerWithString:sourceString];
while (![scanner isAtEnd]) {
NSString *tempString;
[scanner scanUpToCharactersFromSet:escapeCharsSet intoString:&tempString];
if([scanner isAtEnd]){
[destString appendString:tempString];
}
else {
[destString appendFormat:#"%#\\%#", tempString, [sourceString substringWithRange:NSMakeRange([scanner scanLocation], 1)]];
[scanner setScanLocation:[scanner scanLocation]+1];
}
}
Related
I'm doing this to encode my URL in this way,
but its not working,
i got the result in NSLog but its the same url nothing is changing.
Please help me to sort this issue.
below is my code :
NSString *unencodedUrlString =
[#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7"
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#" %#", unencodedUrlString);
Thanks in advance
The comma is a legal URL character, therefore stringByAddingPercentEscapesUsingEncoding leaves "2,7" as it is and does not replace it by "2%2C7".
If you want the comma to be replaced by a percent escape (as I understand from your
comment to the question), you can use CFURLCreateStringByAddingPercentEscapes
instead:
NSString *str = #"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7";
NSString *encoded = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef)(str), NULL, CFSTR(","), kCFStringEncodingUTF8));
NSLog(#"%#", encoded);
Output:
http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2%2C7
The fourth parameter CFSTR(",") specifies that the comma should be replaced by
a percent escape even if it is a legal URL character.
Use this
NSString *str = [NSString stringWithFormat:#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7"];
NSString *path = [str stringByReplacingOccurrencesOfString:#"," withString:#"/"];
NSLog(#"%#",path);
This will do nothing but will make , to /.
for(int i= 0 ;i<[urlsArrray count]; i++)
{
NSString *urlString = [urlsArrray objectAtIndex:i];
NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *urlstring1 = [url absoluteString];
NSArray *parts = [urlstring1 componentsSeparatedByString:#"/"];
NSString *fileName = [parts objectAtIndex:[parts count]-1];
NSMutableString *tempString = [NSMutableString stringWithString:fileName];
// [tempString replaceCharactersInRange:[tempString rangeOfString:#"%20"] withString:#" "];
NSLog(#"file name in temp string: %# word name: %#", tempString, wordNameDB);
NSRange match = [tempString rangeOfString:wordNameDB];
if(match.location != NSNotFound)
{
NSLog(#"match found at %u", match.location);
isAvailable = YES;
break;
}
Hi friends, now my problem is i am getting file name from server..., if file name is having any spaces then it replace '%20' ( i.e ex: "hello world" is actual name but i am getting file name like: "hello%20world") .
1. I am not sure all file names having spaces.
2. And also i am not sure a file may have only one space
so first i have to check the file is having spaces or not, if have then i want to replace all "%20" with #" " string. Please give me any suggestions or code snippets.
OR " THERE IA ANY OTHER WAY TO READ FILE NAMES WITHOUT GETTING '%20' IN THE PLACE OF SPACE(#" ")..... thank you
If you have your file name stored in fileName param, you can use the following:
fileName = [fileName stringByReplacingOccurrencesOfString:#"%20" withString:#" "];
The above code will replace all "%20" with " ". If there are no "%20" in the fileName, you will get back the same string.
Correction:
I was confused with stringByAddingPercentEscapesUsingEncoding mentioned in code and thought you have already used stringByReplacingPercentEscapesUsingEncoding. If you are not using stringByReplacingPercentEscapesUsingEncoding method, you should use that in this case. The above code is useful, only if that is not able to remove any particular string which you want to replace.
What you need is replacing the escape charcters, according to the encoding.
Use this and all your spaces and other URL encoded characters will be converted to what you need.
[#"yourString" stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
THERE IA ANY OTHER WAY TO READ FILE NAMES WITHOUT GETTING '%20' IN THE PLACE OF SPACE(#" ")
Yes, use this:
NSString *newString = [yourstring stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Use this to remove spaces ..
urlString = [urlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
You seem to already have a valid NSURL object representing the file. Getting the filename from a URL is easy:
...
NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *path = [url path];
NSString *filename = [path lastPathComponent];
No fiddling with unescaping percent escapes, URL parsing, and other error prone stuff.
I have NSString #" (\n "Bi_ss" \n) "
I want to get String #"Bi_ss "
Any one has any idea about this ?
Thank you
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
From Cocoanetics...
Take a look at the NSString method stringByReplacingOccurrencesOfString:withString for example, this should be able to perform the basic task you want it to do.
When using NSString's enumerateSubstringsInRange:options:usingBlock: with the options set as NSStringEnumerationByWords it doesn't include symbols such as /* or // which should be treated similarly to words as they are seperated by spaces.
I also tried using NSStringEnumerationByComposedCharacterSequences but it seems to do exactly the same thing even without this option, it simply goes through every single letter.
Is their no way to enumerate through every substring separated by a space? It sounds so simple by no way to do is provided to do this using enumerateSubstringsInRange:options:usingBlock:.
EDIT
I was also using the option NSEnumerationReverse to got through the substrings backwards.
You could use NSScanner for something like this. It's sort of the long way around, but if the enumerate... messages aren't doing it for you, it might be worth looking at.
For example, you could do something like
NSString *output = nil;
NSCharacterSet *whitespaceCharSet = [NSCharacterSet whitespaceCharacterSet];
NSScanner *scanner = [[NSScanner alloc] initWithString:someString];
// should skip leading whitespace and read everything up to the next whitespace
[scanner scanUpToCharactersFromSet:whitespaceCharSet intoSring:&output];
[scanner release];
Sort of a crude example, but the documentation for NSScanner is fairly simple.
Edit: Alternatively, you could do something like this:
NSString *someString = <...>; // get your string somehow
NSCharacterSet *charSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *components = [someString componentsSeparatedByCharactersInSet:charSet];
[components
enumerateObjectsWithOptions:NSEnumerationReverse
usingBlock:^(id obj, NSUInteger index, BOOL *stop) {
// do stuff
}];
I'm trying to replace all multiple whitespace in some text with a single space. This should be a very simple task, however for some reason it's returning a different result than expected. I've read the docs on the NSScanner and it seems like it's not working properly!
NSScanner *scanner = [[NSScanner alloc] initWithString:#"This is a test of NSScanner !"];
NSMutableString *result = [[NSMutableString alloc] init];
NSString *temp;
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
while (![scanner isAtEnd]) {
// Scan upto and stop before any whitespace
[scanner scanUpToCharactersFromSet:whitespace intoString:&temp];
// Add all non whotespace characters to string
[result appendString:temp];
// Scan past all whitespace and replace with a single space
if ([scanner scanCharactersFromSet:whitespace intoString:NULL]) {
[result appendString:#" "];
}
}
But for some reason the result is #"ThisisatestofNSScanner!" instead of #"This is a test of NSScanner !".
If you read through the comments and what each line should achieve it seems simple enough!? scanUpToCharactersFromSet should stop the scanner just as it encounters whitespace. scanCharactersFromSet should then progress the scanner past the whitespace up to the non-whitespace characters. And then the loop continues to the end.
What am I missing or not understanding?
Ah, I figured it out! By default the NSScanner skips whitespace!
Turns out you just have to set charactersToBeSkipped to nil:
[scanner setCharactersToBeSkipped:nil];