Why whitespaceAndNewlineCharacterSet doesn't remove spaces? - iphone

This code SHOULD clean phone number, but it doesn't:
NSLog(#"%#", self.textView.text);
// Output +358 40 111 1111
NSString *s = [self.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#", s);
// Output +358 40 111 1111
Any ideas what is wrong? Any other ways to remove whitespacish characters from text string (except the hard way)?

Try this
NSCharacterSet *dontWantChar = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *string = [[self.textView.text componentsSeparatedByCharactersInSet:dontWantChar] componentsJoinedByString:#""];

The documentation for stringByTrimmingCharactersInSet says:
Returns a new string made by removing from both ends of the
receiver characters contained in a given character set.
In other words, it only removes the offending characters from before and after the string any valid characters. Any "offending" characters are left in the middle of the string because the trim method doesn't touch that part.
Anyways, there are a few ways to do the thing you're trying to do (and #Narayana's answer is good on this, too... +1 to him/her). My solution would be to set your string s to be a mutable string and then do:
[s replaceOccurrencesOfString: #" " withString: #"" options: NSBackwardsSearch range: NSMakeRange( 0, [s length] )];

Related

How to "normalize" an URL replacing any special characters with new ones

In any URL, you can have special characters like *? & ~ : / *
and soon if not already, accentuated characters
What I'd like is to convert ANY url into it's nearest equivalent in pure ASCII character
THEN replacing any remaining spécial charaters by a _
I've tried this looking and inspiring myslef with many examples over the net, but it do not work (for example, using this code, the character "é" is not converted to "e" in #"http://www.mélange.fr/~fermer.php?aa=10&ee=13")
NSMutableCharacterSet *charactersToKeep = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToKeep addCharactersInString:#"://&=~?"];
NSCharacterSet* charactersToRemove = [charactersToKeep invertedSet];
myNSString = [[[myNSString decomposedStringWithCanonicalMapping] componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:#""];
to start, after I will have to convert remaining special characters with _
How may I achieve this ?
As an example (and only for example), I'd like to convert :
http://www.mélange.fr/~fermer.php?aa=10&ee=13
to
http___www.melange.fr__fermer_php_aa_10_ee_13
of course without having to check one by one each possible special or accentued character.
Two thoughts:
To replace accented characters with unaccented ones, there are a couple of candidates:
You can use CFStringTransform:
NSMutableString *mutableString = [string mutableCopy];
CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformStripCombiningMarks, NO);
You could use dataUsingEncoding:allowLossyConversion:
NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
Characters it doesn't know what to do with become ? and but this sometimes replaces one character with multiple characters (e.g. © with (C)), which you may or may not want.
Once you do this international character conversion, it looks like you want replace any non-alphanumeric character (or period) with an underscore, which you could do with a stringByReplacingOccurrencesOfString with a regular expression:
NSString *result = [string stringByReplacingOccurrencesOfString:#"[^a-z0-9\\.]"
withString:#"_"
options:NSRegularExpressionSearch | NSCaseInsensitiveSearch
range:NSMakeRange(0, [string length])];
There are lots of permutations of this regular expression that will accomplish the same thing, but hopefully you get the idea.

how to escape the special characters in iphone development

Can any one guide me how to escape the special characters in iphone development,currently when i use this characters it gets me junk value,
The Following are the charaters :
""$$¢£฿¥₡€₭,
Thanks in advance
You can specify the special characters set you want to ignore in character set.
NSString *oldString = #"dsfas$$$///dfa****";
NSCharacterSet *theCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"+-*!%$/_"];
NSString *newString = [[oldString componentsSeparatedByCharactersInSet:theCharacterSet] componentsJoinedByString:#""];
NSLog(#"newString: %#",newString);

Find words with regEx and then add whitespaces inbetween with Objective-c

I was wondering how to add whitespaces inbetween letters/numbers in a string with Objective-C.
I have the sample code kinda working at the moment. Basically I want to turn "West4thStreet" into "West 4th Street".
NSString *myText2 = #"West4thStreet";
NSString *regexString2 = #"([a-z.-][^a-z .-])";
for(NSString *match2 in [myText2 componentsMatchedByRegex:regexString2 capture:1L]) {
NSString *myString = [myText2 stringByReplacingOccurrencesOfString:match2 withString:#" "];
NSLog(#"Prints out: %#",myString); // Prints out: Wes thStreet // Prints out: West4t treet
}
So in this example, it's replacing what I found in regEx (the "t4" and "hS") with spaces. But I just want to add a space inbetween the letters to separate out the words.
Thanks!
If you wrap parts of your regex patterns in parentheses, you can refer to them as $1, $2, etc in your replacement string (patterns are numbered from left to right, by the order of their opening parenthesis).
NSString *origString = #"West4thStreet";
NSString *newString = [origString stringByReplacingOccurrencesOfRegex:#"(4th)" withString:#" $1 "];
Not sure I understand your broader use case, but that should at least get you going...

How trim the spaces given in a word for textField

I have a word i.e., P roduct Name in a textfield . we have to trim the space between "P" and "r".
Can you please suggest the solution for this.
Thanks in advance.
There is no real reliable solution for this - there is not enough information provided.
(Unless of course you iterated through a word list, which would be, well, horribly inefficient)
P and r could be separate words for all the computer cares..
This can help you to remove spaces between two words.
NSString *string = #"P roduct Name";
NSString *secondString = [string stringByReplacingOccurrencesOfString:#" " withString:#""];
Output: ProductName
If You want to remove white spaces at start and end of your string
NSString *s = #" Product Name ";
s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Output: 'Product Name'

How can I detect if a string contains punctuation marks at the end?

Lets assume I have the string:
"Hello I like your shoes #today...!"
I am tokenizing the string by spaces:
return [string componentsSeparatedByString:#" "];
So my array contains:
Hello
I
like
your
shoes
#today...!
I want to focus on "#today...!" any word that has a # in the prefix I am changing the font color.
How can I make sure that only "#today" has its font color changed?
I would basically like to figure out if a word has a punctuation mark at the end, and change the color for characters before the punctuation mark.
I'm confused by your question. Are you trying to detect string with punctuation marks at the end or with # marks at the beginning?
In any case:
for (NSString *word in [string componentsSeparatedByString:#" "]) {
if ([word hasPrefix:#"#"])NSLog(#"%# starts with #",word);
if ([word hasSuffix:#"!"])NSLog(#"%# end with !",word);
}
You could do something like:
if ([[NSCharacterSet symbolCharacterSet] characterIsMember:[word characterAtIndex:0]]) NSLog(#"%#", word);
This is to test for a symbol at the beginning of the string--to test at the end, you would use [word characterAtIndex:([word length] - 1)]
EDIT: OK, I think I understand the question now. If you want want to only change the color of characters before the color set, you could do something along the lines of:
NSRange punctCharRange = [word rangeOfCharacterFromSet:[NSCharacterSet punctuationCharacterSet]];
for (int i = 0; i < punctCharRange.location; i++) {
//change the color of the character
}
Consider using RegexKitLite and this method:
- (NSRange)rangeOfRegex:(NSString *)regex
options:(RKLRegexOptions)options
inRange:(NSRange)range
capture:(NSInteger)capture
error:(NSError **)error;
The regex you'd want is something like #"#\\S+\\b". This regex says "Find a '#' character followed by 1 or more non-space characters followed by a word boundary".
This would then return the range of the matched regex inside the string to match.
The following code should look from the end of word toward the beginning until it finds a character that is not alphanumeric, test if it found such a character and if so, remove anything after that character. (untested code)
NSString *wordWithoutTrailingNonAlphanum;
NSRange firstNonAlphanumCharFromEnd =
[word rangeOfCharacterFromSet:[NSCharacterSet alphanumericCharacterSet]
options:NSBackwardsSearch];
if (firstNonAlphanumCharFromEnd.location != NSNotFound) {
wordWithoutTrailingNonAlphanum =
[word substringToIndex:(firstNonAlphanumCharFromEnd.location + 1)];
}
I tried tokenizing all words that begin with # and splitting it based on the NSPunctuationCharacterSet. This works, however I lose the punctuation marks.