如何确定字符串中的第一个字符是否是拉丁字母表中的字母

时间:2012-11-06 16:59:55

标签: objective-c

我有一个包含字符串的数组。检查数组中每个字符串的第一个字符是否来自拉丁字母表的最佳方法是什么?

4 个答案:

答案 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}}:

  1. 获取第一项:NSStrings
  2. 获取字母范围:`NSRange lettersRange = [firstString rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet];
  3. 检查范围从字符串开头开始:NSString *firstString = [array objectAtIndex:0];
  4. C - 数组是BOOL isFirstCharALetter = lettersRange.location = 0;的数组(即char *):

    1. 获取第一项:char *[]
    2. 获取字符串的第一个字符:char *firstString = strings[0];
    3. 检查第一个字符是否包含ASCII字符的字母范围: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 @ [ ] $ % ^ ......
}