【问题标题】:I want to remove static text from string - iOS我想从字符串中删除静态文本 - iOS
【发布时间】:2015-02-19 19:02:26
【问题描述】:

嗨,我有一个新闻阅读器,但我不断收到这样的字符串 -

two New York police officers shot dead in 'ambush'

I want the string two New York police officers shot dead in ambush

如何从 & 扫描到 ;然后删除出现的扫描。

我像这样创建了一个扫描仪 -

NSString *webString222222 = filteredTitle2;
        NSScanner *stringScanner222222 = [NSScanner scannerWithString:webString222222];
        NSString *content222222 = [[NSString alloc] init];
        [stringScanner222222 scanUpToString:@"&" intoString:Nil];
        [stringScanner222222 scanUpToString:@";" intoString:&content222222];
        NSString *filteredTitle222 = [content222222 stringByReplacingOccurrencesOfString:content222222 withString:@""];
        NSString *filteredTitle22 = [filteredTitle222 stringByReplacingOccurrencesOfString:@"&" withString:@""];

但是当我执行此代码时,整个文本都会消失!每一个字。 当我在我的 NSLog 中检查标题时,这是唯一的 & 登录那里并且是唯一的;登录那里! 我不确定我哪里出错了。

【问题讨论】:

  • 为什么不把“'”换成“”?
  • 这可能是 question 的副本。
  • 安装文档并阅读。

标签: ios objective-c static symbols nsscanner


【解决方案1】:

如果您遇到的特殊字符都相对一致,您只需将每个子字符串替换为空字符串,如下所示:

NSString *cleansedString = [filteredTitle2 stringByReplacingOccurrencesOfString:@"'" 
                                                                     withString:@""];

【讨论】:

  • & 之后和 ; 之前的内容完全不同。 IDK 那里有什么!
【解决方案2】:

您可以使用NSRegularExpression 构建正确的匹配模式:

NSString *pattern = @"\\&#[0-9]+;";
NSString *str = @"two New York police officers shot dead in 'ambush'";

NSLog(@"Original test: %@",str);
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:pattern
                              options:NSRegularExpressionCaseInsensitive error:&error];
if (error != nil)
{
    NSLog(@"ERror: %@",error);
} 
else 
{
    NSString *replaced = [regex stringByReplacingMatchesInString:str
                                                         options:0
                                                           range:NSMakeRange(0, [str length])
                                                    withTemplate:@""];

    NSLog(@"Replaced test: %@",replaced);
}

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSRegularExpression_Class/index.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2013-10-09
    • 2012-12-22
    • 2022-01-16
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    相关资源
    最近更新 更多