Encoding a comma with stringByAddingPercentEscapesUsingEncoding - objective-c

Why doesn't the comma get encoded? I was expecting it to be %2C.
(lldb) po [#"," stringByAddingPercentEscapesUsingEncoding:4]
(id) $24 = 0x0a8fbfd0 ,

As noted by #DayS, because comma is a legal URL character. However, if you would like to have control over which characters are escaped, look at CFURLCreateStringByAddingPercentEscapes().
NSString *toencode = #",";
NSString *result =
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFTypeRef)toencode,
NULL,
CFSTR(","),
kCFStringEncodingUTF8));
NSLog(#"%#", result);

This method will only replace special characters which aren't valid in a URL. As the comma is a valid one, he'll stay like this.
Try with this string to check :
[#",éà /" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
To replace other characters like comma, you have to do it yourself...

Related

stringByAddingPercentEscapesUsingEncoding does not escape "&"

I am using stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding to pass data to a php script. The problem is if the field has the char '&' in the text lets say: 'someone & cars', only the text "someone" is saved, everything after the '&' doesn't.
To create the string I use [NSString stringWithFormat:], so I have like 5 field in the form and if I use stringbyReplacingOcorrencesOfstring:#"&", what it does is replace the whole string not only the char '&' from the text field, so I get error.
Any ideas?
Unfortunately, stringByAddingPercentEscapesUsingEncoding: doesn't actually escape all necessary URL characters.
Instead, you can use the lower-level CoreFoundation function:
(NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)myString, NULL, (CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding));
or, when using ARC:
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)myString, NULL, (__bridge CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding)));
See this post for an example of a category on NSString that uses this function.
Following works using stringByAddingPercentEncodingWithAllowedCharacters if you want to specifically allow what would be encoded yourself. I'm using after base64 so this works fine.
NSString *charactersToEscape = #"!*'();:#&=+$,/?%#[]\" ";
NSCharacterSet *customEncodingSet = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *url = [NSString stringWithFormat:#"%#", #"http://www.test.com/more/test.html?name=john&age=28"];
NSString *encodedUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:customEncodingSet];

Replace special character or whitespace with -

I want to make every string look like this:
"this-is-string-one"
So main string could contain:
"This! is string, one"
So basicaly replace !?., whitespace and characters like that with "-".
Something like this is best handled by a regular expression:
NSString *someString = #"This! is string, one";
NSString *newString = [someString stringByReplacingOccurrencesOfString:#"[!?., ]+" withString:#"-" options: NSRegularExpressionSearch range:NSMakeRange(0, someString.length)];
NSLog(#"\"%#\" was converted to \"%#\"", someString, newString);
The output will be:
"This! is string, one" was converted to "This-is-string-one"
The regular expression [!?., ]+ means any sequence of one or more of the characters listed between the square brackets.
Update:
If you want to truncate any trailing hyphen then you can do this:
if ([newString hasSuffix:#"-"]) {
newString = [newString substringToIndex:newString.length - 1];
}

How to omit a certain substring out of an NSString?

I would like to know how it is possible to omit a specific substring out an NSString, assuming the NSString does contain that substring.
For example:
Original string: "This is a string but these words should be omitted."
Substring to omit: "but these words should be omitted".
Result string: "This is a string."
Thanks ahead,
iLyrical.
NSString *originalString = #"This is a string but these words should be omitted.";
NSString *substringToOmit = #" but these words should be omitted";
NSString *resultString = [originalString stringByReplacingOccurencesOfString:substringToOmit
withString:#""];
See NSString's stringByReplacingOccurrencesOfString:withString:. You may also want to trim the trailing whitespace with stringByTrimmingCharactersInSet:.

searching and replacing an extended ASCII in a string

a noob question here.
I am trying to make an automatic search and replace process for characters' ASCII values in a string.
so, I have a string constructed from a content of a UITextField
NSString *searchText;
searchText = (mmText.text);
then I do a little loop and check all entered characters for their ASCII values. if they're not in the allowed range I want to search and replace them with something else (? for now)
so let's say I am in the loop and I get to a ASCII 45 character (it's a minus sign):
int asciiCode = 45;
now I would like to find the ASCII 45 character in the string and replace it with a question mark
This is what I am doing at the moment:
NSString *ascStr = [NSString stringWithFormat:#"%c", asciiCode];
NSRange matchSpace;
matchSpace = [searchText rangeOfString: ascStr];
if (matchSpace.location == NSNotFound)
{}
else
NSMutableString *searchandReplace = [NSMutableString stringWithString: searchText];
[searchandReplace replaceCharactersInRange: [searchandReplace rangeOfString: ascStr] withString: #"?"];
mmText.text = searchandReplace;
}
This works fine for a regular ASCII value (0-255), but it doesn't seem to work for the extended ASCII values coming from foreign languages. For example when using the Korean language mode, one of the main character looks like a double crossed W, but when printed via NSLog it looks like a copyright sign. This is probably the reason the search and replace procedure doesn't work for it. It has an ASCII value of 8361.
any ideas ? thank you!
it turns out it was as simple as changing:
NSString *ascStr = [NSString stringWithFormat:#"%c", asciiCode];
to
NSString *ascStr = [NSString stringWithFormat:#"%C", asciiCode];
%c
8-bit unsigned character (unsigned char), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit
%C
16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit

How do I remove '\' characters from my NSString

/images/content/booking_thumbs_uk/s_kl/50000/THB_999_H54007.jpg
changes to:
/images/content/booking_thumbs_uk/s_kl/00000/THB_999_H2470.jpg
NSString* original=#"\\/images\\/content\\/booking_thumbs_uk\\/s_kl\\/50000\\/THB_999_H54007.jpg";
NSString* removed=[original stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSLog(#"%#",removed); // shows /images/content/booking_thumbs_uk/s_kl/00000/THB_999_H2470.jpg
Be very careful, because inside the source code between "..." the backslash has a special meaning. In order to represent an honest backslash, you need to double it, like "\\".
You can use newString = [oldString stringByReplacingOccurrencesOfString:#"\\" withString:#""];