ios 如何查看 NSString 是否以某个其他字符串开头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7934688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:05:53  来源:igfitidea点击:

How to see if an NSString starts with a certain other string?

iosobjective-ciphonensstringnsmutablestring

提问by Rob

I am trying to check to see if a string that I am going to use as URL starts with http. The way I am trying to check right now doesn't seem to be working. Here is my code:

我正在尝试检查我将用作 URL 的字符串是否以 http 开头。我现在尝试检查的方式似乎不起作用。这是我的代码:

NSMutableString *temp = [[NSMutableString alloc] initWithString:@"http://"];
if ([businessWebsite rangeOfString:@"http"].location == NSNotFound){
    NSString *temp2 = [[NSString alloc] init];
    temp2 = businessWebsite;
    [temp appendString:temp2];
    businessWebsite = temp2;
    NSLog(@"Updated BusinessWebsite is: %@", businessWebsite);
}

[web setBusinessWebsiteUrl:businessWebsite];

Any ideas?

有任何想法吗?

回答by Cyrille

Try this: if ([myString hasPrefix:@"http"]).

试试这个:if ([myString hasPrefix:@"http"])

By the way, your test should be != NSNotFoundinstead of == NSNotFound. But say your URL is ftp://my_http_host.com/thing, it'll match but shouldn't.

顺便说一下,你的测试应该是!= NSNotFound而不是== NSNotFound. 但是说你的 URL 是ftp://my_http_host.com/thing,它会匹配但不应该。

回答by JonasG

I like to use this method:

我喜欢使用这种方法:

if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
  //starts with http
}

or even easier:

甚至更容易:

if ([temp hasPrefix:@"http"]) {
    //do your stuff
}

回答by bobics

If you're checking for "http:" you'll probably want case-insensitive search:

如果您正在检查“http:”,您可能需要不区分大小写的搜索:

NSRange prefixRange = 
    [temp rangeOfString:@"http" 
                options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
if (prefixRange.location == NSNotFound)

回答by Richard

Swift version:

迅捷版:

if line.hasPrefix("#") {
  // checks to see if a string (line) begins with the character "#"
}

回答by Hackmodford

This is my solution to the problem. It will remove the letters that are not necessary and is case insensitive.

这是我对问题的解决方案。它将删除不需要且不区分大小写的字母。

    - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [self generateSectionTitles];
}

-(NSArray *)generateSectionTitles {

    NSArray *alphaArray = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", nil];

    NSMutableArray *sectionArray = [[NSMutableArray alloc] init];

    for (NSString *character in alphaArray) {



        if ([self stringPrefix:character isInArray:self.depNameRows]) {
            [sectionArray addObject:character];
        }

    }

    return sectionArray;

}

-(BOOL)stringPrefix:(NSString *)prefix isInArray:(NSArray *)array {

    for (NSString *str in array) {

        //I needed a case insensitive search so [str hasPrefix:prefix]; would not have worked for me.
        NSRange prefixRange = [str rangeOfString:prefix options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
        if (prefixRange.location != NSNotFound) {
            return TRUE;
        }

    }

    return FALSE;

}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

    NSInteger newRow = [self indexForFirstChar:title inArray:self.depNameRows];
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:newRow inSection:0];
    [tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];

    return index;
}

// Return the index for the location of the first item in an array that begins with a certain character
- (NSInteger)indexForFirstChar:(NSString *)character inArray:(NSArray *)array
{
    NSUInteger count = 0;
    for (NSString *str in array) {

        //I needed a case insensitive search so [str hasPrefix:prefix]; would not have worked for me.
        NSRange prefixRange = [str rangeOfString:character options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
        if (prefixRange.location != NSNotFound) {
            return count;
        }
        count++;
    }
    return 0;
}