计算NSString中2个单词之间的所有字符

时间:2014-07-29 11:03:48

标签: ios objective-c cocoa nsstring foundation

是否可以计算NSString中2个单词之间的字符数?这是字符串

NSString *myString = [NSString stringWithFormat:@"This is a test string."];

我想计算单词“This”和单词“string”之间的字符。

这可能吗

5 个答案:

答案 0 :(得分:2)

您可能会这样做:

NSString *myString = [NSString stringWithFormat:@"This is a test string."];

NSInteger charCountBetween = -1;
NSRange thisRange = [myString rangeOfString:@"This"];
NSRange stringRange = [myString rangeOfString:@"string"];
if( thisRange.location != NSNotFound && stringRange.location != NSNotFound )
{
    charCountBetween = fabs(thisRange.location - stringRange.location);
    if( thisRange.location > stringRange.location )
    {
        charCountBetween -= stringRange.length;
    }
    else
    {
        charCountBetween -= thisRange.length;
    }
}

答案 1 :(得分:1)

你必须首先找到范围并从中获取子串

NSString *myString = [NSString stringWithFormat:@"This is a test string."];
NSRange range1 = [myString rangeOfString:@"This"];
NSRange range2 = [myString rangeOfString:@"string"];
NSRange rangeSubString = NSMakeRange(range1.location + range1.length, range2.location - range1.location - range1.length);
NSString *subString = [myString substringWithRange:rangeSubString];

然后你可以计算这个字符串的字符

NSUInteger characterCount = [subString length];

答案 2 :(得分:0)

NSString *myString = @"This is a test !";
NSRange match = [myString rangeOfString: @"This"];
NSRange match1 = [myString rangeOfString: @"test"];

int nbChar = match1.location - match.location;

这是你在找什么?

答案 3 :(得分:0)

试试这个:

NSString *string = @"This is a test string";
NSRange firstRange = [string rangeOfString:@"This"];
NSRange secondRange = [string rangeOfString:@"string"];
if (firstRange.location != NSNotFound &&
    secondRange.location != NSNotFound &&
    secondRange.location > firstRange.location) {
    NSLog(@"Characters between: %d", secondRange.location - (firstRange.location + firstRange.length));
}

答案 4 :(得分:0)

您想要使用NSRange

NSRange range1 = [myString rangeOfString:@"This"];
NSRange range2 = [myString rangeOfString:@"string"];
NSUInteger numberOfChars = range2.location - range1.location;