我从webservice收到一个像下面一个字符串的回复 -
brand = company %% samsung @@ modelnumber = webmodel %% GT1910 @@ Sim = Single %% SingleSim @@ 3g = yes %% Yes @@ wifi = yes %% yes(2.1 mbps upto)
我很难混淆我的回复,如下面的那样 -
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)
如何删除不需要的单词。
答案 0 :(得分: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)并按%%
拆分并使用最后一个值。
答案 1 :(得分: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);
答案 2 :(得分:0)
好吧,我不能马上编写代码,但这就是你要做的事情:
%%
替换为(space)
@@
替换为\n
=
和(space)