I have seen one answer for my task, but I couldnt find it now.
I want to detect whether a string has empty word and contains at least "" or " " (two spaces" or more multiple spaces, OR not.
If not, I would add this to Nsmutablearray.
If yes with empty or at least one space, I would like it not to be written to mutablearray.
How to solve this?
EDIT 12 October 2011:
Guys, thank you.
Again I am sorry that I was unclear about my wish. I wanted to check if a string is empty or contains whitespaces without any character. I have posted my answer below.
Im not sure whether it is the most performant way of doing it but you could split your array and see whether the length is greater than 1:
if ([string componentsSeparatedByString:@" "].count > 1)
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
if( bookmarked.length == 0 )
{
NSLog (@"not allowed: empty");
}
else if ([[bookmarked stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)
{
NSLog (@"not allowed: whitespace(s)");
}
else
{
[bookmarklist addObject:bookmarked];
}
Depends if you're looking for ANY whitespace or just spaces. For spaces you can use:
if( [string length] == 0 ||
!NSEqualRanges( [string rangeofString:@" "],
NSMakeRange(NSNotFound, 0) ) )
{
// either the string is empty or we found a space
} else {
// we didn't find a space and the string is at least of length 1
}
If any whitespace, use the whitespace character set:
if( [string length] == 0 ||
!NSEqualRanges( [string rangeOfCharacterFromSet:
[NSCharacterSet whitespaceCharacterSet]],
NSMakeRange(NSNotFound, 0) ) )
{
// either the string is empty or we found a space
} else {
// we didn't find a space and the string is at least of length 1
}
Replace whitespaceCharacterSet
with whitespaceAndNewlineCharacterSet
if you like.
Look at the documentation for NSString
.
Specifically, look under the section Finding Characters and Substrings for the method you want, probably you want to use – rangeOfString:options:range:
multiple times.
Also, look under the section Replacing Substrings for the method you want, probably you want to use – stringByReplacingOccurrencesOfString:withString:options:range:
Take a look at the NSRegularExpression class and coding examples.
NSString *myString = @"ABC defa jh";
int spaceCount = [[myString componentsSeparatedByString:@" "] count] - 1;
if (!spaceCount) {
// Zero spaces, Do Something
} else if (spaceCount <= 2) {
// 1-2 spaces add this to NSMutableArray (although the wording about what you wanted to do in each case is confusing, so adjust for your needs)
} else {
// 3+ spaces, Do Not add this to NSMutableArray (adjust for your needs)
}