How to check whether a string contains white spaces - iphone

How to check whether a string contains whitespaces in between characters?

use rangeOfCharactersFromSet:
NSString *foo = #"HALLO WELT";
NSRange whiteSpaceRange = [foo rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
if (whiteSpaceRange.location != NSNotFound) {
NSLog(#"Found whitespace");
}
note: this will also find whitespace at the beginning or end of the string. If you don't want this trim the string first...
NSString *trimmedString = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange whiteSpaceRange = [trimmedString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];

You can also follow these steps:
NSArray *componentsSeparatedByWhiteSpace = [testString componentsSeparatedByString:#" "];
If there is any whitespace in your string, then it will separate those and store different components in the array. Now you need to take the count of array. If count is greater than 1, it means there are two components, i.e, presence of white space.
if([componentsSeparatedByWhiteSpace count] > 1){
NSLog(#"Found whitespace");
}

Related

How do I remove the end of an NSMutableString?

I have the following NSMutableString:
#"1*2*3*4*5"
I want to find the first * and remove everything after it, so my string = #"1"; How do I do this?
NSMutableString *string = [NSMutableString stringWithString:#"1*2*3*4*5"];
NSRange range = [string rangeOfString:#"*"];
if (range.location != NSNotFound)
{
[string deleteCharactersInRange:NSMakeRange(range.location, [string length] - range.location)];
}
You could try to divide this string by a separator and get the first object
NSString *result = [[MyString componentsSeparatedByString:#"*"]objectAtIndex:0];
After calling componentsSeparatedByString:#"*" you'll get the array of strings, separated by *,and the first object is right what you need.
Here's yet another strategy, using the very flexible NSScanner.
NSString* beginning;
NSScanner* scanner = [NSScanner scannerWithString:#"1*2*3*4*5"];
[scanner scanUpToString:#"*" intoString:&beginning];
You could use -rangeOfString: to find the index of the first asterisk and use that with -substringToIndex: to extract a substring from the original input. Something like this perhaps...
NSMutableString *input = #"1*2*3*4*5";
// Finds the range of the first instance. See NSString docs for more options.
NSRange firstAsteriskRange = [input rangeOfString:#"*"];
NSString *trimmedString = [input substringToIndex:firstAsteriskRange.location + 1];

Objective-C: Find consonants in string

I have a string that contains words with consonants and vowels. How can I extract only consonants from the string?
NSString *str = #"consonants.";
Result must be:
cnsnnts
You could make a character set with all the vowels (#"aeiouy")
+ (id)characterSetWithCharactersInString:(NSString *)aString
then use the
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
method.
EDIT: This will only remove vowels at the beginning and end of the string as pointed out in the other post, what you could do instead is use
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
then stick the components back together. You may also need to include capitalized versions of the vowels in the set, and if you want to also deal with accents (à á è è ê ì etc...) you'll probably have to include that also.
Unfortunately stringByTrimmingCharactersInSet wont work as it only trim leading and ending characters, but you could try using a regular expression and substitution like this:
[[NSRegularExpression
regularExpressionWithPattern:#"[^bcdefghjklmnpqrstvwx]"
options:NSRegularExpressionCaseInsensitive
error:NULL]
stringByReplacingMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#""]
You probably want to tune the regex and options for your needs.
Possible, for sure not-optimal, solution. I'm printing intermediate results for your learning. Take care of memory allocation (I didn't care). Hopefully someone will send you a better solution, but you can copy and paste this for the moment.
NSString *test = #"Try to get all consonants";
NSMutableString *found = [[NSMutableString alloc] init];
NSInteger loc = 0;
NSCharacterSet *consonants = [NSCharacterSet characterSetWithCharactersInString:#"bcdfghjklmnpqrstvwxyz"];
while(loc!=NSNotFound && loc<[test length]) {
NSRange r = [[test lowercaseString] rangeOfCharacterFromSet:consonants options:0 range:NSMakeRange(loc, [test length]-loc)];
if(r.location!=NSNotFound) {
NSString *temp = [test substringWithRange:r];
NSLog(#"Range: %# Temp: %#",NSStringFromRange(r), temp);
[found appendString:temp];
loc=r.location+r.length;
} else {
loc=NSNotFound;
}
}
NSLog(#"Found: %#",found);
Here is a NSString category that does the job:
- (NSString *)consonants
{
NSString *result = [NSString stringWithString:self];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#"aeiou"];
while(1)
{
NSRange range = [result rangeOfCharacterFromSet:characterSet options:NSCaseInsensitiveSearch];
if(range.location == NSNotFound)
break;
result = [result stringByReplacingCharactersInRange:range withString:#""];
}
return result;
}

How to detect UISearchBar is containing blank spaces only

How to detect if UISearchBar contains only blank spaces not any other character or string and replace it with #""?
You can trim the string with a character set containing whitespace using the NSString stringByTrimmingCharactersInSet message (using the whitespaceCharacterSet):
NSString * searchString = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (![searchString length])
// return ... search bar was just whitespace
You can check as
[yourSearchBar.text isEqualToString:#""]
Hope it helps.
if([searchBar.text isEqualToString:#""] && [searchBar.text length] ==0){
// Blank Space in searchbar
else{
// Do Search
}
Use isEqualToString method of NSString
Use stringByTrimmingCharactersInSet to trim the character from NSString.
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
Use as below.
NSString* myString = mySearchBar.text
myString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Here's how you detect and replace it: (assuming the UISearchField is called searchBar)
NSString*replacement;
if ([searchBar.text isEqualToString:#" "])
{
replacement = [NSString stringByReplacingOccurancesOfString:#" " withString:#""];
}
searchBar.text = replacement;
Have a look in the Apple Documentation for NSString for more.
Edit:
If you have more than once space, do this:
NSString *s = [someString stringByReplacingOccurrencesOfString:#" "
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [someString length])
];
searchBar.text = s;
This worked for me: if you are using #"" or length already to control say a button then this version really does detect the whitespace, if a space has been entered...
if([activeField.text isEqualToString:#" "] && [activeField.text length] ==1){
// Blank Space in searchbar
{
// an alert example
}

How to test a string for text

I would like to test a string to see if anywhere it contains the text "hello". I would like the test to not take into account capitalization. How can I test this string?
Use the below code as reference to find check for a substring into a string.
NSString* string = #"How to test a string for text" ;
NSString* substring = #"string for" ;
NSRange textRange;
textRange =[string rangeOfString:substring options:NSCaseInsensitiveSearch];
if(textRange.location != NSNotFound)
{
//Does contain the substring
}
-[NSString rangeOfString: options:] will do it.
NSRange range = [string rangeOfString:#"hello" options:NSCaseInsensitiveSearch];
BOOL notFound = range.location==NSNotFound;
I am assuming all words are separated by a space, and that there is no punctuation. If there is punctuation.
NSArray *dataArray = [inputString componentsSeparatedByString:#" "];
for(int i=0; i<[dataArray count]){
if([[dataArray objectAtIndex:i] isEqualToString:#"hello"]){
NSLog(#"hello has been found!!!");
}
}
I haven't tested this but it should work in theory.
Check out the docs for ways to remove punctuation and make the string all lower case. This should be pretty straight-forward.
Other solutions here are good but you should really use a regex,
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^(hello)*$"
options:NSRegularExpressionCaseInsensitive
error:&error];
Docs are here: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

Remove newline character from first line of NSString

How can I remove the first \n character from an NSString?
Edit: Just to clarify, what I would like to do is:
If the first line of the string contains a \n character, delete it else do nothing.
ie: If the string is like this:
#"\nhello, this is the first line\nthis is the second line"
and opposed to a string that does not contain a newline in the first line:
#"hello, this is the first line\nthis is the second line."
I hope that makes it more clear.
[string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]
will trim your string from any kind of newlines, if that's what you want.
[string stringByReplacingOccurrencesOfString:#"\n" withString:#"" options:0 range:NSMakeRange(0, 1)]
will do exactly what you ask and remove newline if it's the first character in the string
This should do the trick:
NSString * ReplaceFirstNewLine(NSString * original)
{
NSMutableString * newString = [NSMutableString stringWithString:original];
NSRange foundRange = [original rangeOfString:#"\n"];
if (foundRange.location != NSNotFound)
{
[newString replaceCharactersInRange:foundRange
withString:#""];
}
return [[newString retain] autorelease];
}
Rather than creating an NSMutableString and using a few retain/release calls, you can use only the original string and simplify the code by using the following instead: (requires 10.5+)
NSRange foundRange = [original rangeOfString:#"\n"];
if (foundRange.location != NSNotFound)
[original stringByReplacingOccurrencesOfString:#"\n"
withString:#""
options:0
range:foundRange];
(See -stringByReplacingOccurrencesOfString:withString:options:range: for details.)
The result of the last call method call can even be safely assigned back to original IF you autorelease what's there first so you don't leak the memory.