Replace special character or whitespace with - - objective-c

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];
}

Related

How can I replace special characters by regex and Objective-C?

String: abc2_2fkf-lo
Now I want to use regex to delete the special characters as _ and -
The expect string as I want: abc22fkflo
Use stringByReplacingOccurrencesOfString.
NSString *string = #"abc2_2fkf-lo";
NSString *updated = [string stringByReplacingOccurrencesOfString:#"[-_]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
This replaces any occurrence of a - or _ character with the empty string.
Note that if you want to match a - character using [ ] in a regular expression, the - needs to be the first character to avoid its normal special use as a character range operator.

Encoding a comma with stringByAddingPercentEscapesUsingEncoding

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...

Objective-C – Replace newline sequences with one space

How can I replace newline (\n) sequences with one space.
I.e the user has entered a double newline ("\n\n") I want that replaced with one space (" "). Or the user has entered triple newlines ("\n\n\n") I want that replaced with also one space (" ").
Try this:
NSArray *split = [orig componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
split = [split filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"length > 0"]];
NSString *res = [split componentsJoinedByString:#" "];
This is how it works:
First line splits by newline characters
Second line removes empty items inserted for multiple separators in a row
Third line joins the strings back using a single space as the new separator
3 times more performant than using componentsSeparatedByCharactersInSet
NSString *fixed = [original stringByReplacingOccurrencesOfString:#"\\n+"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, original.length)];
Possible alternative regex patterns:
Replace only space: [ ]+
Replace space and tabs: [ \\t]+
Replace space, tabs and newlines: \\s+
Replace newlines: \\n+
As wattson says you can do this with NSRegularExpression but the code is quite verbose so if you want to do this at several places I suggestion you to do a helper method or even a NSString category with method like -[NSString stringByReplacingMatchingPattern:withString:] or something similar.
NSString *string = #"a\n\na";
NSLog(#"%#", [[NSRegularExpression regularExpressionWithPattern:#"\\n+"
options:0
error:NULL]
stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#" "]);
Use a regular expression, something like "s/\n+/\w/" (a replace which will match 1 or more newline character and replace with a single white space)
this question has a link to a regex library, but there is NSRegularExpression available too

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:.

replacing escape character sequences in objective c

I have a query that returns a string, as well as an escape character sequence. (ex. "USA\"")
I am using stringByReplacingOccurrencesOfString in this fashion:
[theCountry stringByReplacingOccurrencesOfString:#"\"" withString:#""];
But it is still leaving behind a set of quotes. and if I were to try the method again to remove them:
[theCountry stringByReplacingOccurrencesOfString:#""" withString:#""];
I would have an incomplete set of quotes...
I need to get rid of both the slash and the double quotes.
Any thoughts?
You need to escape the backslash:
NSString* foo = #"USA\\\"";
NSLog(#"String [%#]", foo);
foo = [foo stringByReplacingOccurrencesOfString:#"\\\"" withString:#""];
NSLog(#"String [%#]", foo);
Results in
2009-11-02 09:15:24.403 test[6098:903] String [USA\"]
2009-11-02 09:15:24.406 test[6098:903] String [USA]