我有一个包含字符串的数组。检查数组中每个字符串的第一个字符是否来自拉丁字母表的最佳方法是什么?
答案 0 :(得分:7)
基本上你可以使用这样的字符集:
NSString* string = @"This is a string";
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
if([letters characterIsMember:[string characterAtIndex:0]]) {
// This is a letter
}
这个例子说明了一切: - )
答案 1 :(得分:2)
这取决于你是在处理Objective-C对象还是C(我假设是Objective-C,但我们两个都可以)
Objective-C - 数组是NSArray
的{{1}}:
NSStrings
NSString *firstString = [array objectAtIndex:0];
C - 数组是BOOL isFirstCharALetter = lettersRange.location = 0;
的数组(即char *
):
char *[]
char *firstString = strings[0];
char firstChar = firstString[0];
答案 2 :(得分:1)
简单的oneliner:
if ( [string length] && iswalpha([string characterAtIndex:0]) )
{
// stuff
}
答案 3 :(得分:0)
//Defines only alphabet that we will compare with
NSCharacterSet *alphaBetFromAToZ = [NSCharacterSet letterCharacterSet];
NSCharacterSet *numberFrom0To9 = [NSCharacterSet decimalDigitCharacterSet];
//My string
NSString *myStringToCheck = @"String";
//Check if string is not empty and if so, make it a not empty string otherwise the app could throw up an exception
myStringToCheck = ([myStringToCheck length] == 0) ? @" ":myStringToCheck;
//Check if first string is from the alphabet
if ([alphaBetFromAToZ characterIsMember:[myStringToCheck characterAtIndex:0]])
{
//First character is from the alphabet
}
else if ([numberFrom0To9 characterIsMember:[myStringToCheck characterAtIndex:0]])
{
//First character is a number
}
else
{
//First character is NOT from the alphabet and also is not a number, is something like @ [ ] $ % ^ ......
}