【问题标题】:Check if string is already exist and add a number as suffix to the string in the array?检查字符串是否已经存在并将数字作为后缀添加到数组中的字符串?
【发布时间】:2016-06-01 13:57:38
【问题描述】:

我的名字是“Ryan”,下次输入“Ryan”时应该检查它的值,所以它应该是“Ryan_1”。同样,它应该检查是否有人再次添加“Ryan”,它应该将其更改为“Ryan_2”。

例子:

nameArray = ["Ryan","John","Ryan_2","Rhonda","Ryan_3","Kylie","Ryan_4","John_2"];

我正在使用下面的代码,它在第一次添加名称时运行良好。

但是当我回到该部分并编辑值时,例如:我将 Ryan_2 更改为“xyz”并再次考虑保留“Ryan”,保存的值将变为“Ryan_4”,而它应该是“Ryan_2”数组。假设我现在将“Ryan_4”更改为“somenewName”,其他重复名称的编号也会重新排列。

NSMutableArray *array = [[NSMutableArray alloc]init];

int occurrences = 0;

for(NSString *string in nameArray) {
    if ([value isKindOfClass:[NSString class]]) {
        if ([string containsString:value]) {
            [array addObject:string];
        }

        occurrences+= ([string containsString:value] ? 1 : 0);
    }
}       

if ([value isKindOfClass:[NSString class]]) {
    if (![value isEqualToString:@""]) {
        if (occurrences > 1) {
            value = [value stringByAppendingFormat:@"_%d", occurrences];
        }
    }
}

【问题讨论】:

  • 那么为了解决这个问题,您考虑过将基于 occurrences 的实现更改为什么?
  • 你真的需要这个命名方案吗?有更简单和更快的选项可以保证唯一的名称...
  • @Wain 感谢您的回复。实际上,用户将从相机拍摄多张照片并将它们保存在画廊中,从画廊视图中,他们可以通过键盘的音频功能为照片添加名称,因此有时他们会为 n 幅图片添加相同的名称。例如:来自西方、来自西方、来自西方。所以那个时候我们需要用编号自动保存 From west。
  • 什么是标题数组?
  • 你能保证你的邪恶用户不会选择'Ryan_2'用户名吗?

标签: ios objective-c


【解决方案1】:

我会推荐这样的扩展:

extension NSMutableArray {
public func appendWithSuffix(strNewEntry:String) {
    var n = 1
    var new = strNewEntry
    if self.containsObject(strNewEntry) {
        new = strNewEntry + "_\(n)"
        while self.containsObject( new ){
            n += 1
            new = strNewEntry + "_\(n)"
        }
    }
    self.addObject( new )
}}

它会寻找一个完全匹配的,如果没有找到就插入,即它会添加“Ryan_5”而不是“Ryan”,“John_3”而不是“John”等等。

另一种方法可能是遍历所有条目以进行比较或使用"namexy".hasPrefix("Ryan") 过滤数组以获得要插入的名称的最大索引。

【讨论】:

  • @谢谢迈克尔,它在更新数组中的名称时工作正常。但是在删除时它不会刷新计数。我想我需要添加一个删除检查并重新排列顺序。
【解决方案2】:
- (IBAction)SaveText:(id)sender
{

if (array.count==0)
    {
        [array addObject:_txtAddText.text];
    }else
    {

        for(NSString *string in array)
        {
            if ([string containsString:_txtAddText.text] )
            {
                count = count+1;
              NSString *Localstring =[NSString stringWithFormat:@"%@%d",[string stringByAppendingString:@"_"],count];
                 NSLog(@"%@",Localstring);
                [array addObject:Localstring];
                break;
            }else
            {
                [array addObject:_txtAddText.text];
            }
        }

    }

    NSLog(@"%@",array);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    相关资源
    最近更新 更多