你可以試試這個還有:(會建議嘗試在一個單獨的測試應用程序)
我假設你的目標行:
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*)"
這種模式有三個字符後面緊跟着兩個數字,然後用空間(S)下劃線和空間(S)的任何行相匹配。
您可以使用這些功能,然後根據自己的需要:
firstMatchInString:options:range:
matchesInString:options:range:
numberOfMatchesInString:options:range:
希望它能幫助。
快樂編碼和閱讀!
編輯:
我已經更新代碼,但我有疑問的沒有。您在評論中指定的標記中的字符。那麼這會給你一個關於如何解決這個問題的想法。
請再次用2個例子來解釋你的問題和要求。我格式化了你的問題,我錯過了什麼? –
我想「xyz_」後打印的字符我想打印所有包含在每個字符之間的空間像xyz_後charachter: AAAAAAAA BBBBBBBB CCCCCCC 不說「的NSArray * lineFile = [contentFile componentsSeparatedByString :@」「] ..我嘗試它不工作 – DD007
你要打印 「在你的例子22 AAAAAAAAAAA bbbbbbbbbbb ccccccccccccccc ddddddddddddd」 –