你也可以试试这个:(建议在单独的测试应用程序中尝试)
我假设你的目标线:
xyz_ 22 aaaaaaaaaaa bbbbbbbbbbb ccccccccccccccc ddddddddddddd
总是以“xyz_ 22”开头。在这里查看:(另请参阅评论)
// prepared a string similar to what you already have
NSMutableString *xmlfile = [[NSMutableString alloc] initWithFormat:@"%@\n%@\n%@\n%@\n%@\n%@\n%@\n%@\n%@",
@"asasasasasas",
@"wewewewewewe",
@"xyz_ 22 aaaaaaaaaaa bbbbbbbbbbb ccccccccccccccc ddddddddddddd",
@"fgfgfgfgfgfgfg",
@"ererererererer",
@"",
@"abc_ 12 bbbbbbbbbb dddddddd",
@"jkjkjkjkjkjkjk",
@"lalallalalalal"];
NSLog(@"%@", xmlfile); // check out by printing (optional)
NSArray *arr = [xmlfile componentsSeparatedByString:@"\n"]; // first break with NEWLINE character
NSLog(@"%@",arr); // check out by printing (optional)
for (NSString *str in arr) // traverse all lines
{
if([str hasPrefix:@"xyz_ 22"]) // if it starts with "xyz_ 22"
{
NSMutableArray *mArr = [[NSMutableArray alloc] initWithArray:[[str stringByReplacingOccurrencesOfString:@"xyz_ 22 " withString:@""] componentsSeparatedByString:@" "]];
for(int i=0; i< [mArr count];i++ )
{
NSString *tag;
if([[mArr objectAtIndex:i] length] > 3)
{
// If more than three i.e., aaaaa then write <aaa>aaaaaaa<aaa>
tag = [[mArr objectAtIndex:i] substringWithRange:NSMakeRange(0, 3)];
}
else
{
// If less than three i.e., aa then pick <aa>aa<aa> or
a then pick <a>a<a>
tag = [mArr objectAtIndex:i];
}
NSString *s= [[NSString alloc] initWithFormat:@"<%@>%@<%@>", tag, [mArr objectAtIndex:i], tag];
[mArr removeObjectAtIndex:i];
[mArr insertObject:s atIndex:i];
}
NSLog(@"%@", mArr); // prints output
}
}
如果行首不固定为“xyz_ 22”,则需要查看NSRegularExpression类并使用它而不是使用hasPrefix
.
此示例模式可以帮助您:
@"^(.{3}\_\s*\d{2}\s*)"
此模式匹配包含三个字符后跟下划线和空格后跟两位数字后跟空格的任何行。
您可以根据需要使用这些功能中的任何一个:
firstMatchInString:选项:范围:
匹配字符串:选项:范围:
numberOfMatchesInString:选项:范围:
希望能帮助到你。
快乐的编码和阅读!!!
编辑:
我已经更新了代码,但我怀疑没有。您在评论中指定的标签中的字符数。好吧,这将使您了解如何解决此问题。