remove specific characters from NSString - iphone

I wants to remove specific characters or group substring from NSString.
mean
NSString *str = #" hello I am #39;doing Parsing So $#39;I get many symbols in &my response";
I wants remove #39; and $#39; and & (Mostly these three strings comes in response)
output should be : hello I am doing Parsing So i get many symbols in my response
Side Question : I can't write & #39; without space here, because it converted in ' <-- this symbol. so i use $ in place of & in my question.

you should use [str stringByReplacingOccurrencesOfString:#"#39" withString:#""]
or you need replace strings of concrete format like "#number"?

try below code ,i think you got whatever you want simply change the charecterset,
NSString *string = #"hello I am #39;doing Parsing So $#39;I get many symbols in &my response";
NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:#"#39;$&"];
NSString *result = [[string componentsSeparatedByCharactersInSet:trim] componentsJoinedByString:#""];
NSLog(#"%#", result);

Related

Splitting NSString into NSArray on component '\n'

I'm trying to split a NSString into a NSArray, and it's proving difficult even though this is normally an easy task. I'm receiving data, from my Python server and forming a NSString on the iPhone client. I noticed sometimes when I receive multiple messages from my Python server I would NSLog a string like:
Project: textOne
textTwo
After adding the string into a NSArray and calling NSLog on that array the string would show:
Project: (
"textOne\ntextTwo\n"
)
After playing with code:
[str componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
[str componentsSeparatedByString:#"\n"];
[str substringToIndex:[str length]-1];
I have managed to produce NSArray's with content:
Project: (
"textOne",
textTwo
)
And
Project: (
"textOne",
textTwo,
""
)
I cannot produce a NSArray with content:
Project: (
textOne,
textTwo
)
If anyone could help, I'd greatly appreciate it.
Trim your string before separating into components using stringByTrimmingCharactersInSet: to prevent empty components at the end or beginning.
NSCharacterSet *separatorSet = [NSCharacterSet newlineCharacterSet];
NSString *trimmed = [str stringByTrimmingCharactersInSet:separatorSet];
[trimmed componentsSeparatedByCharactersInSet:separatorSet];
This won't prevent empty strings in the middle of your array.
Another solution would be to filter out any undesired strings after separating into components.

Parsing URL Using Regular Expression

I need to parse a URL in the following format:
http://www.example.com/?method=example.method&firstKey=firstValue&id=1893736&thirdKey=thirdValue
All I need is the value of 1893736 within &id=1893736.
I need to do the parsing in Objective-C for my iPhone project. I understand it must have something to do with regular expression. But I just have no clue how to do it.
Any suggestions would be appreciated. :)
You don't need a regex for this. You can try something like this
NSString *url = #"http://www.example.com/?method=example.method&firstKey=firstValue&id=1893736&thirdKey=thirdValue";
NSString *identifier = nil;
for (NSString *arg in [[[url pathComponents] lastObject] componentsSeparatedByString:#"&"]) {
if ([arg hasPrefix:#"id="]) {
identifier = [arg stringByReplacingOccurrencesOfString:#"id=" withString:#""];
}
}
NSLog(#"%#", identifier);
Don't use regular expressions. Use NSURL to reliably extract the query string and then use this answer's code to parse the query string.
Use this:
.*/\?(?:\w*=[^&]*&)*?(?:id=([^&]*))(?:&\w*=[^&]*)*
And grap first group: \1. You will obtain 1893736.
Simplifying
If the id can consist of only digits:
.*/\?(?:\w*=[^&]*&)*?(?:id=(\d*))(?:&\w*=[^&]*)*
If you don't care about capturing uninterested groups (use \3 or id in this case):
.*/\?(\w*=.*?&)*?(id=(?<id>\d*))(&\w*=.*)*
More simpler version (use \3):
.*/\?(.*?=.*?&)*(id=(\d*))(&.*?=.*)*
Instead of using regex, you can split the string representation of your NSURL instance. In your case, you can split the string by the appersand (&), loop the array looking for the prefix (id=), and get the substring from the index 2 (which is where the = ends).

Junk character in Webview

I am getting html content as a string in my webservice response which contains "&nbsp" in it. When I display that data in webview, "&nbsp" is converted in junk character. Please let me know how to solve it.
You have to read the string as NSUTF8 encoded string and then pass the string to web view using "loadHTML" method mentioned in UIWebView.
Not only that, if you want to display special characters like copy right, double quotes etc or other language characters in the HTML, you have to use UTF8 encoding.
Use the stringByReplacingPercentEscapesUsingEncoding: method of NSString
like :
NSString *decoded = [yourString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Also to remove use
[yourString stringByReplacingOccurrencesOfString:#" " withString:#" "];
stringByReplacingOccurrencesOfString is deprecated from ios 9
let decoded = yourString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

StringByAddingPercentEscapes not working on ampersands, question marks etc

I'm sending a request from my iphone-application, where some of the arguments are text that the user can enter into textboxes. Therefore, I need to HTML-encode them.
Here's the problem I'm running into:
NSLog(#"%#", testText); // Test & ?
testText = [testText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", testText); // Test%20&%20?
As you can see, only the spaces are encoded, making the server disregard everything past the ampersand for the argument.
Is this the advertised behaviour of stringByAddingPercentEscapes? Do I have to manually replace every special character with corresponding hex code?
Thankful for any contributions.
They are not encoded because they are valid URL characters.
The documentation for stringByAddingPercentEscapesUsingEncoding: says
See CFURLCreateStringByAddingPercentEscapes for more complex transformations.
I encode my query string parameters using the following method (added to a NSString category)
- (NSString *)urlEncodedString {
CFStringRef buffer = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
NULL,
CFSTR("!*'();:#&=+$,/?%#[]"),
kCFStringEncodingUTF8);
NSString *result = [NSString stringWithString:(NSString *)buffer];
CFRelease(buffer);
return result;
}

displaying german characters in iphone

i have following string coming in the json response.
"Gas-Heizung-Sanit\u00e4r" so how to display it. i want to display that \u00e4 as a german character..
NSString *str = "Gas-Heizung-Sanit\u00e4r";
NSLog(#"%c",str);
it only prints the german character.
the following works
NSString *str = #"Gas-Heizung-Sanit\u00e4r";
NSLog(#"%#",str);
You forgot the # on the string and also the %c is for a character, you should use the %# for a string