0

我收到来自 web 服务的响应,如下所示的字符串 -

品牌=公司%%samsung@@modelnumber=webmodel%%GT1910@@Sim=Single%%SingleSim@@3g=yes%%Yes@@wifi=yes%%yes(最高2.1 mbps)

我很困惑将我的回复格式化如下 -

brand=samsung
modelnumber=GT1910
Sim=SingleSim
3g=Yes
wifi=(2.1 mbps upto)

我试图删除特殊字符(@@ and %%)

specialString = [specialString stringByReplacingOccurrencesOfString:@"@@" withString:@"\n"];
specialString = [specialString stringByReplacingOccurrencesOfString:@"%%" withString:@"\n"];
specialString= [specialString stringByReplacingOccurrencesOfString:@" " withString:@""];

我的输出是 -

brand=company
samsung
modelnumber=webmodel
GT1910
Sim=Single
SingleSim
3g=yes
Yes
wifi=yes
(2.1 mbps upto)

如何删除不需要的单词。

4

3 回答 3

4

您不能使用简单的查找和替换,因为您不需要原始字符串的某些部分。

未经测试,但这可能会起作用:

NSArray *parts = [specialstring componentsSeparatedByString:@"@@"];
NSMutableArray *result = [[NSMutableArray alloc] init];
for(NSString *piece in parts) {
    NSArray *pairs = [piece componentsSeparatedByString:@"="];
    if([pairs count] > 1) {
        NSString *key = [pairs objectAtIndex:0];
        NSString *values = [pairs objectAtIndex:1];
        NSArray *avalues = [values componentsSeparatedByString:@"%%"];
        [result addObject:[NSString stringWithFormat:@"%@=%@", key, [avalues lastObject]]];
    }
}

NSLog(@"%@", [result componentsJoinedByString:@"\n"]);
// [result release]; // Uncomment if ARC is turned off

首先拆分@@并迭代数组。然后拆分=以获取左侧的键(索引 0)。取右侧(索引 1)并拆分%%并使用最后一个值。

于 2012-11-20T05:28:35.603 回答
1

像下面这样修剪它会起作用

NSString *strRes = @"brand=company%%samsung@@modelnumber=webmodel%%GT1910@@Sim=Single%%SingleSim@@3g=yes%%Yes@@wifi=yes%%yes(2.1 mbps upto)";
strRes = [strRes stringByReplacingOccurrencesOfString:@"=" withString:@"--"];
strRes = [strRes stringByReplacingOccurrencesOfString:@"@@" withString:@"\n"];
NSRange rangeForTrim;
while ((rangeForTrim = [strRes rangeOfString:@"--[^%%]+%%" options:NSRegularExpressionSearch]).location != NSNotFound)
    strRes = [strRes stringByReplacingCharactersInRange:rangeForTrim withString:@"="];

NSLog(@"%@",strRes);
于 2012-11-20T05:45:12.540 回答
0

好吧,我不能马上写代码,但这是你必须做的:

  • 全部替换%%(space)
  • 全部替换@@\n
  • =删除和之间的所有单词(space)
于 2012-11-20T05:21:26.963 回答