我正在尝试检查我将用作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];
有什么想法吗?
答案 0 :(得分:323)
试试这个:if ([myString hasPrefix:@"http"])
。
顺便说一句,您的测试应该是!= NSNotFound
而不是== NSNotFound
。但是说你的网址是ftp://my_http_host.com/thing
,它会匹配,但不应该。
答案 1 :(得分:22)
我喜欢使用这种方法:
if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
//starts with http
}
甚至更容易:
if ([temp hasPrefix:@"http"]) {
//do your stuff
}
答案 2 :(得分:6)
如果您正在检查“http:”,则可能需要不区分大小写的搜索:
NSRange prefixRange =
[temp rangeOfString:@"http"
options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
if (prefixRange.location == NSNotFound)
答案 3 :(得分:2)
Swift版本:
if line.hasPrefix("#") {
// checks to see if a string (line) begins with the character "#"
}
答案 4 :(得分:0)
这是我解决问题的方法。它将删除不必要的字母,并且不区分大小写。
- (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;
}