2011-08-25 6 views
7

¿Cómo elimino cierto texto de NSString como "http: //"? Necesita ser exactamente en ese orden. ¡Gracias por tu ayuda!Eliminar http: // de NSString

Aquí está el código que estoy usando, sin embargo, el http: // no se elimina. En cambio, aparece http://http://www.example.com. ¿Que debería hacer? ¡Gracias!

NSString *urlAddress = addressBar.text; 
[urlAddress stringByReplacingOccurrencesOfString:@"http://" withString:@""]; 
urlAddress = [NSString stringWithFormat:@"http://%@", addressBar.text]; 
NSLog(@"The user requested this host name: %@", urlAddress); 
+1

Está añadiendo de nuevo la misma cadena. No es necesario utilizar la tercera línea si desea eliminar http: // – Nitish

+0

Si el usuario no ingresa http: //, entonces UIWebView funcionará. Sin embargo, si el usuario ingresa http: //, entonces UIWebView no funcionará. Al eliminar cualquier http: // que haya y luego reinsertarlo una vez, se me garantiza que NSString se verá así: http: // www.google.com –

+0

posible duplicación de [Eliminar parte de un NSString] (http://stackoverflow.com/questions/4423248/remove-part-of-an-nsstring) –

Respuesta

18

¿Le gusta?

NSString* stringWithoutHttp = [someString stringByReplacingOccurrencesOfString:@"http://" withString:@""]; 

(si desea eliminar el texto en el único principio, hacer lo jtbandes dice - el código anterior sustituirá a las apariciones en el medio de la cadena, así)

+0

@Jack Humphries ver mi respuesta y editar – Krishnabhadra

+0

@Jack Humphries - Krishnabhadra tiene razón, no asigna el valor cambiado de urlAddress cuando lo hace stringByReplacingOccurrencesOfString: – SVD

+0

Genial, gracias por tu ayuda! –

4
NSString *newString = [myString stringByReplacingOccurrencesOfString:@"http://" 
                  withString:@"" 
                  options:NSAnchoredSearch // beginning of string 
                   range:NSMakeRange(0, [myString length])] 
3

Otra forma es:

NSString *str = @"http//abc.com"; 
NSArray *arr = [str componentSeparatedByString:@"//"]; 
NSString *str1 = [arr objectAtIndex:0];  // http 
NSString *str2 = [arr objectAtIndex:1];  // abc.com 
+0

no funcionará, si str es como 'abc.com' – HotJard

3

si http: // se encuentra al principio de la cadena que puede utilizar

NSString *newString = [yourOriginalString subStringFromIndex:7]; 

o bien como sugirió SVD

EDIT: Después de ver pregunta Editar

cambiar esta línea

[urlAddress stringByReplacingOccurrencesOfString:@"http://" withString:@""]; 

a

urlAddress = [urlAddress stringByReplacingOccurrencesOfString:@"http://" withString:@""]; 
0

O

+(NSString*)removeOpeningTag:(NSString*)inString tag:(NSString*)inTag { 
    if ([inString length] == 0 || [inTag length] == 0) return inString; 
    if ([inString length] < [inTag length]) {return inString;} 
    NSRange tagRange= [inString rangeOfString:inTag]; 
    if (tagRange.location == NSNotFound || tagRange.location != 0) return inString; 
    return [inString substringFromIndex:tagRange.length]; 
} 
0

Aquí hay otra opción;

NSMutableString *copiedUrl = [[urlAddress mutablecopy] autorelease]; 
[copiedUrl deleteCharactersInRange: [copiedUrl rangeOfString:@"http://"]]; 
0

NSString * newString = [cadena stringByReplacingOccurrencesOfString: @ "http: //" withString: @ ""];

7

he aquí una solución que se encarga de http & https:

NSString *shortenedURL = url.absoluteURL; 

    if ([shortenedURL hasPrefix:@"https://"]) shortenedURL = [shortenedURL substringFromIndex:8]; 
    if ([shortenedURL hasPrefix:@"http://"]) shortenedURL = [shortenedURL substringFromIndex:7]; 
0

En caso de que desee recortar ambos lados y también escribir menos código:

NSString *webAddress = @"http://www.google.co.nz"; 

// add prefixes you'd like to filter out here 
NSArray *prefixes = [NSArray arrayWithObjects:@"https:", @"http:", @"//", @"/", nil]; 

for (NSString *prefix in prefixes) 
    if([webAddress hasPrefix:prefix]) webAddress = [webAddress stringByReplacingOccurrencesOfString:prefix withString:@"" options:NSAnchoredSearch range:NSMakeRange(0, [webAddress length])]; 

// add suffixes you'd like to filter out here 
NSArray *suffixes = [NSArray arrayWithObjects:@"/", nil]; 

for (NSString *suffix in suffixes) 
    if([webAddress hasSuffix:suffix]) webAddress = [webAddress stringByReplacingOccurrencesOfString:suffix withString:@"" options:NSBackwardsSearch range:NSMakeRange(0, [webAddress length])]; 

prefijos Este código quitar especificados de el frente y sufijos desde la parte posterior (como una barra inclinada). Simplemente agregue más subcadenas a la matriz de prefijo/sufijo para filtrar por más.

0

Swift 3

Para reemplazar todas las ocurrencias:

let newString = string.replacingOccurrences(of: "http://", with: "") 

Para reemplazar las ocurrencias en el inicio de la cadena:

let newString = string.replacingOccurrences(of: "http://", with: "", options: .anchored) 
0

Hola chicos poco tarde pero vengo con una forma genérica Digamos:

NSString *host = @"ssh://www.somewhere.com"; 
NSString *scheme = [[[NSURL URLWithString:host] scheme] stringByAppendingString:@"://"]; 
// This extract ssh and add :// so we get @"ssh://" note that this code handle any scheme http, https, ssh, ftp .... 
NSString *stripHost = [host stringByReplacingOccurrencesOfString:scheme withString:@""]; 
// Result : stripHost = @"www.somewhere.com" 
0

una forma más general:

- (NSString*)removeURLSchemeFromStringURL:(NSString*)stringUrl { 
    NSParameterAssert(stringUrl); 
    static NSString* schemeDevider = @"://"; 

    NSScanner* scanner = [NSScanner scannerWithString:stringUrl]; 
    [scanner scanUpToString:schemeDevider intoString:nil]; 

    if (scanner.scanLocation <= stringUrl.length - schemeDevider.length) { 
     NSInteger beginLocation = scanner.scanLocation + schemeDevider.length; 
     stringUrl = [stringUrl substringWithRange:NSMakeRange(beginLocation, stringUrl.length - beginLocation)]; 
    } 

    return stringUrl; 
} 
Cuestiones relacionadas