Remove '\' from the string in IOS application - iphone

I am getting a url as string from json response with backslash character. I want to remove the '\' character from the url. I build up the code but it is not working. The code is here:
NSString *responseData = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:url] encoding:NSUTF8StringEncoding];
NSString* encodedString = [responseData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#" ,encodedString);
// here encodedString is a url which is showing crctly in output and need to trim the \ character.
// NSString* str = [NSString stringWithFormat: #"encodedString"];
// str = [str stringByReplacingOccurrencesOfString:#"?" withString:#""];
// NSLog(#"Response ==> %#" , str);
encodedString = [encodedString stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSLog(#"Response ==> %#" ,encodedString);
but I am not able to remove the characters.

If you want to remove the spaces and \ character, it is better to remove them from responseData.
NSString *responseData = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:url] encoding:NSUTF8StringEncoding];
responseData = [responseData stringByReplacingOccurrencesOfString:#" " withString:#""];
responseData = [responseData stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSString* encodedString = [responseData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

try this:
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"\\"];
encodedString = [[encodedString componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSLog(#"%#", encodedString);
Hope this will help

Try this way;
Assuming your string contains a \, in string used double as for escaping the next \
NSMutableString *string=[NSMutableString stringWithString:#"hi this i\\s good"];
//NSMutableString *string=[NSMutableString stringWithString:encodedString];
[string replaceOccurrencesOfString:#"\\" withString:#"" options:1 range:NSMakeRange(0, string.length)];
NSLog(#"%#",string);

Related

How to parse numbers from NSString?

NSString *numberVector = #"( 1, 2, 3, 4)";
I want to get NSMutableArray from these numbers.
How can I do this?
This is the simpler one, convert it to json string first then convert is to array using NSJSONSerialization
NSString *numberVector = #"( 1, 2, 3, 4)";
numberVector = [numberVector stringByReplacingOccurrencesOfString:#"(" withString:#"["];
numberVector = [numberVector stringByReplacingOccurrencesOfString:#")" withString:#"]"];
NSError* error;
NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:[numberVector dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
Update
This will work for both #"( 1, 2, 3, 4)" and #"(\n 1,\n 2,\n 3,\n 4\n)" as json string can have new line and spaces.
P.S This will work for iOS 5.0 or greater for other iOS you can use SBJSON or other parsing library available.
If you know that this is exactly your format and don't have to be flexible in the amount of spaces, brackets or commas:
NSCharacterSet *trimSet = [NSCharacterSet characterSetWithCharactersInString:#" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:trimSet];
NSArray *numbers = [numberVector componentsSeparatedByString:#", "];
try like this it'l works fine for any type of data it accepts only numbers.
NSString *numberVector = #"(\n 1,\n 2,\n 3,\n 4\n)";
NSString *onlyNumbers = [numberVector stringByReplacingOccurrencesOfString:#"[^0-9,]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [numberVector length])];
NSArray *numbers=[onlyNumbers componentsSeparatedByString:#","];
NSLog(#"%#",numbers);
See the code below, it should work:
NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString:#" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:cSet];
//specify delimiter below
NSArray *numbers = [numberVector componentsSeparatedByString:#", "];
With this:
NSString *numberVector = #"( 1, 2, 3, 4)";
EDIT
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"&([^;])*;" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [numberVector stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
NSArray *listItems = [[modifiedString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsSeparatedByString:#", "]

Change parts of an NSString

I have a urlString that is: http://www.youtube.com/watch?v=5kdEhVtNFPo
I want to be able to change it into this: http://www.youtube.com/v/5kdEhVtNFPo
How would I go about doing that? I'm not sure if I should use the instance methods substringWithRange: or substringFromIndex:
I tried this which removes the first part and just leaves the video id (it removes http://www.youtube.com/watch?v=) now I just need to add http://www.youtube.com/v/ to the start of the string.
NSString *newUrlString = [urlString substringFromIndex:31];
NSString* newUrl = [oldUrl stringByReplacingOccurrencesOfString:#"watch?v=" withString:#"v/"];
Please note that this only works as long as the URL won't contain more instances of the string "watch?v=".
I'll propose a different way that may be more flexible on the inputs you give it:
- (NSString) newURLStringForOldURLString:(NSString *)oldURLString
{
NSString *newURLString = nil;
NSURL *url = [[NSURL alloc] initWithString:oldURLString];
NSString *query = [url query]; /* v=5kdEhVtNFPo */
NSArray *fieldValuePairs = [query componentsSeparatedByString:#"&"];
for (NSString *pair in fieldValuePairs) {
NSArray *components = [pair componentsSeparatedByString:#"="];
NSString *field = [components objectAtIndex:0];
NSString *value = [components objectAtIndex:1];
if ([field isEqualToString:#"v"]) {
newURLString = [NSString stringWithFormat:#"%#://%#:%#/%#/%#", [url scheme], [url domain], [url port], field, value];
break;
}
}
[url release];
return newURLString;
}
To be flexible enough, you could use NSRegularExpression:
NSString *str = #"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *pattern = #"((?:http:\\/\\/){0,1}www\\.youtube\\.com\\/)watch\\?v=([:alnum:]+)";
NSString *template = #"$1v/$2";
NSRegularExpression *regexp = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *newStr = [regexp stringByReplacingMatchesInString:str
options:0 range:NSMakeRange(0, [str length]) withTemplate:template];
NSLog(#"Replaced: %#", newStr);
Another alternative :
NSString *str3 = #"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *outputString;
NSRange range = [str3 rangeOfString:#"watch?v="];
if(range.location != NSNotFound)
{
outputString = [str3 stringByReplacingCharactersInRange:range withString:#"v/"];
NSLog(#"%#",outputString);
}

Convert Unicode character to NSString

I have received string from webservice which contains Unicode character. I want to convert that To plain NSString. so How can i do that?
ex: "This isn\u0092t your bike"
So how can remove unicode and replace it with its equal special symbol characted.
The output would be : "This isn't your bike"
char cString[] = "This isn\u2019t your bike";
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"result string: %#", string);
This should work.
UPDATE FOR THE COMMENT:
The unicode character specified by you is not supported in all fonts.
http://www.fileformat.info/info/unicode/char/92/fontsupport.htm
But this one does.
http://www.fileformat.info/info/unicode/char/2019/fontsupport.htm
Thats why it throws an error.
NSString *final_url = [NSString stringWithFormat:url];
final_url = [final_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:final_url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:120.0];
NSURLResponse *response;
NSError *error = [[NSError alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *objJSON = [SBJSON new];
NSMutableDictionary *objDataDic = [objJSON objectWithString:strResponse error:nil];
There is a library which does conversion
https://github.com/alexaubry/HTMLString. It will convert all kind of Unicode character.
let escapedSnack = "Fish & Chips"
let snack = escapedSnack.removingHTMLEntities // "Fish & Chips"

Why doesn't stringByReplacingPercentEscapesUsingEncoding: convert L%C3%A9on back to Léon?

I have the following:
modifiedTitle = #"Léon";
modifiedTitle = [modifiedTitle stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", modifiedTitle);
Converted, it now shows as L%C3%A9on.
When I run the following it doesn't convert it back:
NSMutableString *searchText = [NSMutableString stringWithString:modifiedTitle];
[searchText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", searchText);
It still shows as L%C3%A9on.
Anyone know why?
Because stringByReplacingPercentEscapesUsingEncoding: returns a new string. Try this:
NSMutableString *searchText = [NSMutableString stringWithString:modifiedTitle];
NSString *newText = [searchText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", newText);

NSXMLParser problem with "&"(Ampersand) character

My NSXMLParsing is not working because of "&" character.. my code s below .any help please ?
NSString *myRequestString = [NSString stringWithFormat:#"http://abc.com/def/webservices/aa.php?family_id=%d",self.passFamilyId];
//NSLog(#"Requested Service = %#",myRequestString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:myRequestString]];
[request setHTTPMethod: #"POST" ];
NSData *downloadedData = [ NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
//NSString *contentString = [str stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
//NSLog (#"string is :%#" ,str);
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
// Call the XMLParsers's initXMLParse method.
ClientDetailXmlParser *parser = (ClientDetailXmlParser*)[[ClientDetailXmlParser alloc] initXMLParser];
[xmlParser setDelegate:parser];
BOOL success = [xmlParser parse];
// Check for XML parsing.
if(success)
{
NSLog(#"No Errors in clientDetailXml.xml");
}
else
{
NSLog(#"Error Error Error in clientDetailXml.xml!!!");
}
[parser release];
parser = nil;
if (objClientAddUpdate != nil) {
[objClientAddUpdate createBubbleList];
}
Replace
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
//NSString *contentString = [str stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
With:
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
NSString *contentString = [str stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSData * data=[contentString dataUsingEncoding:NSUTF8StringEncoding];
Very similar to sepehr-mahmoudian's answer, but instead of replace any & you should really just replace & characters that are unescaped, to do this you can use a regexp:
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
//NSString *contentString = [str stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
With:
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
NSRange searchedRange = NSMakeRange(0, [str length]);
NSString *pattern = #"&(?!(#[0-9]{2,4}|[A-z]{2,6});)";
NSError *error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
str = [regex stringByReplacingMatchesInString:str options:0 range:searchedRange withTemplate:#"&"];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
Here's what worked for me:
NSString *response = [[NSString alloc]initWithData:dataResponse encoding:NSUTF8StringEncoding];
NSString *newResponse = [response stringByReplacingOccurrencesOfString:#"&amp:" withString:#"AND"];
NSData *dataObj = [newResponse dataUsingEncoding:NSUTF8StringEncoding];
If I replaced it with symbol '&', the response would be correct, but it would throw parsing error: 68. So I had to use 'and'.