gpt4 book ai didi

ios - 带有选项问题的 StringByReplacingOccurrencesOfString

转载 作者:行者123 更新时间:2023-11-29 12:35:42 28 4
gpt4 key购买 nike

我想用其他一些字符串替换出现的以下格式的字符串。此操作应在 for 循环中发生。

这里的 fullString 看起来像这样

There are some other things ... Child_name_13 and Child_name_12     there are some other things ...... Child_name_1 some other things ... Child_name_12 some other things.. Child_name_6 some other things ... Child_name_7

我想要做的是,将“Child_name_1”、“Child_name_12”、“Child_name_7”等替换为从 arrOfChildren 返回的相关子名称。

我的做法如下。

for(int i=0; i<[arrOfChildren count]; i++){
NSString *strChildName = [[arrOf15Children objectAtIndex:i] objectForKey:@"Name"];

fullString = [fullString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"child_name_%d",i+1] withString:strChildName options:NSCaseInsensitiveSearch range:NSMakeRange(0, [fullString length])];
}

问题是,我得到的输出是这样的(假设 child 的名字是 Ben、Randy、Amil、Sanj、Paul、Mark、Ayen、Sid、Don、Yun、Xun、Xin、Nik, jack )

There are some other things ... Ben3 and Ben2     there are some other things ...... Ben some other things ... Ben2 some other things..  Mark some other things ... Ayen

但我希望它是这样的

There are some other things ...Nik and Xin  there are some other things ...... Ben some other things ... Xin some other things.. Mark some other things ... Ayen

我希望,你会得到这个问题。

最佳答案

问题与: [NSString stringWithFormat:@"child_name_%d",i+1]

因为 Child_name_1 将匹配 Child_name_13

这个问题有不同的解决方案。

1) 多次替换:首先替换匹配数字大于等于 10 的项目,然后替换剩余的项目。

for(int i=9; i<[arrOfChildren count]; i++){
NSString *strChildName = [[arrOf15Children objectAtIndex:i] objectForKey:@"Name"];

fullString = [fullString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"child_name_%d",i+1] withString:strChildName options:NSCaseInsensitiveSearch range:NSMakeRange(0, [fullString length])];
}
for(int i=0; i<max(9,[arrOfChildren count]); i++){
NSString *strChildName = [[arrOf15Children objectAtIndex:i] objectForKey:@"Name"];

fullString = [fullString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"child_name_%d",i+1] withString:strChildName options:NSCaseInsensitiveSearch range:NSMakeRange(0, [fullString length])];
}

2) 将正则表达式 ( <a href="https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html" rel="noreferrer noopener nofollow">NSRegularExpression</a> ) 与类似 [...] expression = @"child_name_[0-9]+[^0-9]" 的表达式一起使用会更加稳健.

正则表达式有点棘手,但投入学习它们将使您在字符串处理方面拥有“超能力”!

关于ios - 带有选项问题的 StringByReplacingOccurrencesOfString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26400785/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com