目标C:如何提取字符串的一部分(例如以'#'开头)

时间:2011-07-26 05:52:19

标签: objective-c ios hash nsstring substring

我有一个字符串,如下所示,

NSString * aString = @"This is the #substring1 and #subString2 I want";

如何只选择以'#'开头的文本(以空格结尾),在本例中为'subString1'和'subString2'?

注意:为清晰起见,编辑了问题

7 个答案:

答案 0 :(得分:56)

您可以使用NSScanner分割字符串。此代码将循环遍历字符串并使用子字符串填充数组。

NSString * aString = @"This is the #substring1 and #subString2 I want";
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanUpToString:@"#" intoString:nil]; // Scan all characters before #
while(![scanner isAtEnd]) {
    NSString *substring = nil;
    [scanner scanString:@"#" intoString:nil]; // Scan the # character
    if([scanner scanUpToString:@" " intoString:&substring]) {
        // If the space immediately followed the #, this will be skipped
        [substrings addObject:substring];
    }
    [scanner scanUpToString:@"#" intoString:nil]; // Scan all characters before next #
}
// do something with substrings
[substrings release];

以下是代码的工作原理:

  1. 扫描到#。如果找不到,扫描仪将位于字符串的末尾。
  2. 如果扫描仪位于字符串的末尾,我们就完成了。
  3. 扫描#字符,使其不在输出中。
  4. 扫描到一个空格,扫描的字符存储在substring中。如果#是最后一个字符,或者后面紧跟一个空格,则该方法将返回NO。否则它将返回YES。
  5. 如果扫描了字符(方法返回YES),请将substring添加到substrings数组。
  6. GOTO 1

答案 1 :(得分:33)

[aString substringWithRange:NSMakeRange(13, 10)] 

会给你substring1

您可以使用以下方式计算范围:

NSRange startRange = [aString rangeOfString:@"#"];
NSRange endRange = [original rangeOfString:@"1"];

NSRange searchRange = NSMakeRange(startRange.location , endRange.location);
[aString substringWithRange:searchRange] 

会给你substring1

了解更多: Position of a character in a NSString or NSMutableString

http://iosdevelopertips.com/cocoa/nsrange-and-nsstring-objects.html

答案 2 :(得分:11)

非常简单易懂的版本,避免使用NSRange内容:

NSArray * words = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
NSMutableArray * mutableWords = [NSMutableArray new];
for (NSString * word in words){
    if ([word length] > 1 && [word characterAtIndex:0] == '#'){
        NSString * editedWord = [word substringFromIndex:1];
        [mutableWords addObject:editedWord];
    }
}

答案 3 :(得分:5)

假设您要查找以磅开头的第一个字符串,并以空格结尾,这可能会起作用。我没有XCode在我面前,所以请原谅我,如果语法错误或长度偏离1:

-(NSString *)StartsWithPound:(NSString *)str {
    NSRange range = [str rangeOfString:@"#"];
    if(range.length) {
        NSRange rangeend = [str rangeOfString:@" " options:NSLiteralSearch range:NSMakeRange(range.location,[str length] - range.location - 1)];
        if(rangeend.length) {
            return [str substringWithRange:NSMakeRange(range.location,rangeend.location - range.location)];
        }
        else
        {
            return [str substringFromIndex:range.location];
        }
    }
    else {
        return @"";
    }
}

答案 4 :(得分:3)

另一个简单的解决方案:

NSRange hashtag = [aString rangeOfString:@"#"];
NSRange word = [[aString substringFromIndex:hashtag.location] rangeOfString@" "];
NSString *hashtagWord = [aString substringWithRange:NSMakeRange(hashtag.location, word.location)];

答案 5 :(得分:1)

这就是我要做的事情:

NSString *givenStringWithWhatYouNeed = @"What you want to look through";
NSArray *listOfWords = [givenStringWithWhatYouNeed componentsSeparatedByString:@" "];
for (NSString *word in listOfWords) {
    if ([[word substringWithRange:NSMakeRange(0, 1)]isEqualToString:@"#"]) {
        NSString *whatYouWant = [[word componentsSeparatedByString:@"#"]lastObject];
    }
}

然后,您可以使用whatYouWant实例执行所需操作。如果您想知道它是哪个字符串(如果它是子字符串1或2),请检查word数组中listOfWords字符串的索引。

我希望这会有所帮助。

答案 6 :(得分:0)

选择NSString中以“#”开头的所有单词的一般而简单的代码是:

NSString * aString = @"This is the #substring1 and #subString2 ...";
NSMutableArray *selection=@[].mutableCopy;
while ([aString rangeOfString:@"#"].location != NSNotFound)
{
    aString = [aString substringFromIndex:[aString rangeOfString:@"#"].location +1];
    NSString *item=([aString rangeOfString:@" "].location != NSNotFound)?[aString substringToIndex:[aString rangeOfString:@" "].location]:aString;
    [selection addObject:item];
}

如果您仍需要原始字符串,则可以复制。 如果所选项目是最后一个单词

,则使用内联条件