从 NSString 中删除 http://

发布于 2024-12-01 07:50:25 字数 476 浏览 3 评论 0原文

如何从 NSString 中删除某些文本,例如“http://”?它需要完全按照这个顺序。感谢您的帮助!

这是我正在使用的代码,但是 http:// 并未删除。相反,它会显示 http://http://www.example.com。我应该怎么办?谢谢!

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

How do I remove certain text from a NSString such as "http://"? It needs to be exactly in that order. Thanks for your help!

Here is the code I am using, however the http:// is not removed. Instead it appears http://http://www.example.com. What should I do? Thanks!

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

时光瘦了 2024-12-08 07:50:25

像这样?

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

(如果您只想删除开头的文本,请执行 jtbandes 所说的操作 - 上面的代码也将替换字符串中间出现的文本)

Like this?

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

(if you want to remove text at the beginning only, do what jtbandes says - the code above will replace occurrences in the middle of the string as well)

九命猫 2024-12-08 07:50:25

这是一个处理 http 和 http 的解决方案。 https:

    NSString *shortenedURL = url.absoluteURL;

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

Here's a solution which takes care of http & https:

    NSString *shortenedURL = url.absoluteURL;

    if ([shortenedURL hasPrefix:@"https://"]) shortenedURL = [shortenedURL substringFromIndex:8];
    if ([shortenedURL hasPrefix:@"http://"]) shortenedURL = [shortenedURL substringFromIndex:7];
愿得七秒忆 2024-12-08 07:50:25
NSString *newString = [myString stringByReplacingOccurrencesOfString:@"http://"
                                                          withString:@""
                                                             options:NSAnchoredSearch // beginning of string
                                                               range:NSMakeRange(0, [myString length])]
NSString *newString = [myString stringByReplacingOccurrencesOfString:@"http://"
                                                          withString:@""
                                                             options:NSAnchoredSearch // beginning of string
                                                               range:NSMakeRange(0, [myString length])]
孤千羽 2024-12-08 07:50:25

如果 http:// 位于字符串的开头,您可以使用

 NSString *newString  = [yourOriginalString subStringFromIndex:7];

或者按照 SVD 建议

编辑:看到问题后编辑

将此行更改

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

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

if http:// is at the start of the string you can use

 NSString *newString  = [yourOriginalString subStringFromIndex:7];

or else as SVD suggested

EDIT: AFter seeing question EDIT

change this line

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

to

urlAddress  = [urlAddress stringByReplacingOccurrencesOfString:@"http://" withString:@""];
等风来 2024-12-08 07:50:25

另一种方法是:

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

Another way is :

NSString *str = @"http//abc.com";  
NSArray *arr = [str componentSeparatedByString:@"//"];  
NSString *str1 = [arr objectAtIndex:0];       //   http  
NSString *str2 = [arr objectAtIndex:1];       //   abc.com
走野 2024-12-08 07:50:25

由于该线程仍然处于活动状态并出现在我的搜索中,以从 URL(不是 NSString)中删除前缀...如果您从 URL 开始,则会有一行:

String(url.absoluteString.dropFirst((url.scheme?.count ?? -3) + 3))

Since the thread is still active and showed up in my search to remove the prefix from a URL (not NSString)... there is a one-liner if you are starting with a URL:

String(url.absoluteString.dropFirst((url.scheme?.count ?? -3) + 3))
源来凯始玺欢你 2024-12-08 07:50:25

这是另一种选择;

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

Here is another option;

NSMutableString *copiedUrl = [[urlAddress mutablecopy] autorelease];
[copiedUrl deleteCharactersInRange: [copiedUrl rangeOfString:@"http://"]];
等待我真够勒 2024-12-08 07:50:25

如果您希望修剪两侧并编写更少的代码:

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

此代码将从前面删除指定的前缀并从后面删除后缀(如尾部斜杠)。只需向前缀/后缀数组添加更多子字符串即可过滤更多内容。

In case you wish to trim both sides and also write less code:

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

This code will remove specified prefixes from the front and suffixes from the back (like a trailing slash). Simply add more substrings to the prefix/suffix array to filter for more.

南渊 2024-12-08 07:50:25

Swift 3

用于替换所有出现的位置:

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

用于替换字符串开头的出现位置:

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

Swift 3

For replacing all occurrences:

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

For replacing occurrences at the start of the string:

let newString = string.replacingOccurrences(of: "http://", with: "", options: .anchored)
寂寞花火° 2024-12-08 07:50:25

对于那些使用 swift 并已经到达这里的人。

extension String {

   func withoutHttpPrefix() -> String {
       var idx: String.Index?;
       if self.hasPrefix("http://www.") {
          idx = self.index(startIndex, offsetBy: 11)
       } else if hasPrefix("https://www.") {
           idx = self.index(startIndex, offsetBy: 12)
       } else if self.hasPrefix("http://") {
          idx = self.index(startIndex, offsetBy: 7)
       } else if hasPrefix("https://") {
           idx = self.index(startIndex, offsetBy: 8)
       }

       if idx != nil {
           return String(self[idx!...])
       }
       return self
   }
}

For those using swift and have arrived here.

extension String {

   func withoutHttpPrefix() -> String {
       var idx: String.Index?;
       if self.hasPrefix("http://www.") {
          idx = self.index(startIndex, offsetBy: 11)
       } else if hasPrefix("https://www.") {
           idx = self.index(startIndex, offsetBy: 12)
       } else if self.hasPrefix("http://") {
          idx = self.index(startIndex, offsetBy: 7)
       } else if hasPrefix("https://") {
           idx = self.index(startIndex, offsetBy: 8)
       }

       if idx != nil {
           return String(self[idx!...])
       }
       return self
   }
}
海拔太高太耀眼 2024-12-08 07:50:25

此字符串扩展添加了一个 removeHTTPPrefix() 方法,该方法通过拆分字符串从 URL 中删除 http://https:// 前缀位于 :// 并返回其后的部分,如果未找到分隔符则返回原始字符串:

extension String {    
   func removeHTTPPrefix() -> String {
       return self.components(separatedBy: "://").last ?? self
   }
}

let url = "https://example.com"
let result = url.removeHTTPPrefix()
// result: "example.com"

let plainString = "example.com"
let result2 = plainString.removeHTTPPrefix()
// result2: "example.com" (no change, since there's no "http://" or "https://")

This String extension adds a removeHTTPPrefix() method that removes the http:// or https:// prefix from a URL by splitting the string at :// and returning the part after it, or the original string if no separator is found:

extension String {    
   func removeHTTPPrefix() -> String {
       return self.components(separatedBy: "://").last ?? self
   }
}

let url = "https://example.com"
let result = url.removeHTTPPrefix()
// result: "example.com"

let plainString = "example.com"
let result2 = plainString.removeHTTPPrefix()
// result2: "example.com" (no change, since there's no "http://" or "https://")
伊面 2024-12-08 07:50:25

或者

+(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]; 
}

OR

+(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]; 
}
柏拉图鍀咏恒 2024-12-08 07:50:25

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

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

一种更通用的方法:

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

One more general way:

- (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;
}
寻找我们的幸福 2024-12-08 07:50:25

大家好,有点晚了,但我有一个通用的方法
比方说:

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"

Hi guys bit late but I come with a generic way
Let's say:

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"
心意如水 2024-12-08 07:50:25

这将删除任何方案,包括 http、https 等。

NSRange dividerRange = [str rangeOfString:@"://"];
NSString *newString = [str substringFromIndex:NSMaxRange(dividerRange)];

This will remove any scheme including http, https, etc.

NSRange dividerRange = [str rangeOfString:@"://"];
NSString *newString = [str substringFromIndex:NSMaxRange(dividerRange)];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文