[英]Replacing instances of a character with two different characters in Objective-C
我在數據庫中有大量NSString,這些NSString傳遞給iOS應用程序中的視圖控制器。 它們的格式為“這是具有$特殊格式的$內容的消息”。
但是,我需要在特殊格式的開頭更改為'[',在結尾更改為']'時更改'$'。 我有一種可以使用NSScanner的感覺,但是到目前為止,我所有的嘗試都產生了奇怪的串聯字符串!
有沒有一種簡單的方法可以識別由'$'封裝的子字符串並將其替換為開始/結束字符? 請注意,許多NSString具有多個“ $”子字符串。
謝謝!
您可以使用正則表達式:
NSMutableString *str = [@"Hello $World$, foo $bar$." mutableCopy];
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"\\$([^$]*)\\$"
options:0
error:NULL];
[regex replaceMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:@"[$1]"];
NSLog(@"%@", str);
// Output:
// Hello [World], foo [bar].
模式@"\\\\$([^$]*)\\\\$"
搜索
$<zero_or_more_characters_which_are_not_a_dollarsign>$
然后將所有出現的內容替換為[...]
。 該模式包含許多反斜杠,因為$
必須在正則表達式模式中轉義。
如果要創建新字符串而不是修改原始字符串,則還有stringByReplacingMatchesInString
。
我認為replaceOccurrencesOfString:
無法工作,因為您有start $和end $。
但是,如果用[string componentsSeperatedByString:@"$"]
分隔字符串,則會得到一個子字符串數組,因此第二個字符串就是您的“ $特殊格式的$”字符串
這應該工作!
NSString *str = @"This is a message with $specially formatted$ content";
NSString *original = @"$";
NSString *replacement1 = @"[";
NSString *replacement2 = @"]";
BOOL start = YES;
NSRange rOriginal = [str rangeOfString: original];
while (NSNotFound != rOriginal.location) {
str = [str stringByReplacingCharactersInRange: rOriginal withString:(start?replacement1:replacement2)];
start = !start;
rOriginal = [str rangeOfString: original];
}
NSLog(@"%@", str);
享受編程!
// string = @"This is a $special markup$ sentence."
NSArray *components = [string componentsSeparatedByString:@"$"];
// sanity checks
if (components.count < 2) return; // maybe no $ characters found
if (components.count % 2) return; // not an even number of $s
NSMutableString *out = [NSMutableString string];
for (int i=0; i< components.count; i++) {
[out appendString:components[i]];
[out appendString: (i % 2) ? @"]" : @"[" ];
}
// out = @"This is a [special markup] sentence."
試試這個
NSMutableString *string=[[NSMutableString alloc]initWithString:@"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];
NSMutableString *string=[[NSMutableString alloc]initWithString:@"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];
BOOL open=YES;
for (NSUInteger i=0; i<[string length];i++) {
if ([string characterAtIndex:i]=='$') {
if (open) {
[string replaceCharactersInRange:NSMakeRange(i, 1) withString:@"["];
open=!open;
}
else{
[string replaceCharactersInRange:NSMakeRange(i, 1) withString:@"]"];
open=!open;
}
}
}
NSLog(@"-->%@",string);
輸出:
-->This is a message with [specially formatted] content. This is a message with [specially formatted] content
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.