2011-10-28 12 views
138

estoy tratando de comprobar si una cadena que voy a utilizar como la URL empieza por http. La forma en que estoy tratando de verificar en este momento no parece estar funcionando. Aquí está mi código:¿Cómo ver si un NSString comienza con una cierta otra cadena?

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]; 

¿Alguna idea?

Respuesta

310

Prueba esto: if ([myString hasPrefix:@"http"]). Por favor, su prueba debería ser != NSNotFound en lugar de == NSNotFound. Pero supongamos que su URL es ftp://my_http_host.com/thing, coincidirá pero no debería.

+0

Sí que lo era. Debería haber notado la cosa! = Antes, pero al final fue el hasPrefix el que funcionó. Gracias por el consejo, marcaré la tuya como la respuesta correcta tan pronto como me permita. – Rob

22

me gusta utilizar este método:

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

o incluso más fácil:

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

Eso también es bueno. De esta manera es un poco más flexible, así, gracias por el comentario – Rob

+2

Esto se bloqueará si la cadena de temperatura es de menos de 5 caracteres. El índice comienza en 0. Entonces, esta no es una buena respuesta. Además, el ejemplo tiene una discrepancia en el recuento de caracteres: "http" no tiene 5 caracteres. La insensibilidad a mayúsculas y minúsculas también debe considerarse. – Daniel

+0

@Daniel ¿Qué estás diciendo? ¿Por qué 5? Esto no es un NSArray ... ¡El índice 4 es el 4º personaje, no el 5º! ¿Alguna vez has visto Http o hTtP? Las mayúsculas y minúsculas no son relevantes. También la pregunta fue sobre comprobar si la cadena comienza con http, no sobre la cadena que es más corta que 4 caracteres. hasPrefix: es mejor, pero esto funciona igual de bien. Deja de quejarte – JonasG

5

Si usted está comprobando para "http:" es probable que desee búsqueda sensible a las mayúsculas:

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

Esta es mi solución al problema. Eliminará las letras que no son necesarias y no distingue entre mayúsculas y minúsculas.

- (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; 
} 
2

versión Swift:

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

No sé por qué se votó negativamente ... esta es la manera simple de hacerlo. La mayoría de los nuevos desarrolladores de iOS probablemente usarán Swift de aquí en adelante, y el OP nunca dijo que solo se pidieran las respuestas de Objective-C. – Richard

+0

"No sé por qué se votó negativamente", probablemente porque la sintaxis es incorrecta. En caso de ser 'si line.hasPrefix ("prefijo")' '{} –

+0

Gracias por señalar una sintaxis más simple, pero que se pone() alrededor de una sentencia if no es mala sintaxis. Para algunos de nosotros los veteranos, lee más claramente, y funciona exactamente igual. 'if (line.hasPrefix (" # ")) {}' funciona igual de bien. – Richard

Cuestiones relacionadas