我有一个 NSString 对象,例如:- ($45,0000)
现在我想知道这个字符串是否包含 ()
我怎样才能做到这一点?
您是否要查找它是否包含至少一个(
or )
?您可以使用-rangeOfCharacterFromSet:
:
NSCharacterSet *cset = [NSCharacterSet characterSetWithCharactersInString:@"()"];
NSRange range = [mystr rangeOfCharacterFromSet:cset];
if (range.location == NSNotFound) {
// no ( or ) in the string
} else {
// ( or ) are present
}
如果给定的字符串包含给定的字符,下面的方法将返回 Yes
-(BOOL)doesString:(NSString *)string containCharacter:(char)character
{
return [string rangeOfString:[NSString stringWithFormat:@"%c",character]].location != NSNotFound;
}
您可以按如下方式使用它:
NSString *s = @"abcdefg";
if ([self doesString:s containCharacter:'a'])
NSLog(@"'a' found");
else
NSLog(@"No 'a' found");
if ([self doesString:s containCharacter:'h'])
NSLog(@"'h' found");
else
NSLog(@"No 'h' found");
输出:
2013-01-11 11:15:03.830 CharFinder[17539:c07] 'a' 发现
2013-01-11 11:15:03.831 CharFinder[17539:c07] 找不到“h”
- (bool) contains: (NSString*) substring {
NSRange range = [self rangeOfString:substring];
return range.location != NSNotFound;
}
我在代码中使用了您的问题的通用答案。此代码包括以下规则: 1. 没有特殊字符 2. 至少一个大写字母和一个小英文字母 3. 至少一个数字数字
BOOL lowerCaseLetter,upperCaseLetter,digit,specialCharacter;
int asciiValue;
if([txtPassword.text length] >= 5)
{
for (int i = 0; i < [txtPassword.text length]; i++)
{
unichar c = [txtPassword.text characterAtIndex:i];
if(!lowerCaseLetter)
{
lowerCaseLetter = [[NSCharacterSet lowercaseLetterCharacterSet] characterIsMember:c];
}
if(!upperCaseLetter)
{
upperCaseLetter = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:c];
}
if(!digit)
{
digit = [[NSCharacterSet decimalDigitCharacterSet] characterIsMember:c];
}
asciiValue = [txtPassword.text characterAtIndex:i];
NSLog(@"ascii value---%d",asciiValue);
if((asciiValue >=33&&asciiValue < 47)||(asciiValue>=58 && asciiValue<=64)||(asciiValue>=91 && asciiValue<=96)||(asciiValue>=91 && asciiValue<=96))
{
specialCharacter=1;
}
else
{
specialCharacter=0;
}
}
if(specialCharacter==0 && digit && lowerCaseLetter && upperCaseLetter)
{
//do what u want
NSLog(@"Valid Password %d",specialCharacter);
}
else
{
NSLog(@"Invalid Password %d",specialCharacter);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Please Ensure that you have at least one lower case letter, one upper case letter, one digit and No Any special character"
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
为什么总是使用 NSCharactorSet ?这是简单而强大的解决方案
NSString *textStr = @"This is String Containing / Character";
if ([textStr containsString:@"/"])
{
NSLog(@"Found!!");
}
else
{
NSLog(@"Not Found!!");
您可以使用
NSString rangeOfString: (NSString *) string
见这里:https ://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html%23//apple_ref/occ/instm/NSString/rangeOfString :
如果 NSRange 返回的属性 'location' 等于 NSNotFound,则该字符串不包含传递的字符串(或字符)。