【问题标题】:Is it possible to remove a string which is used many times in uitextview but delete only single one without affecting others是否可以删除在 uitextview 中多次使用但仅删除单个而不影响其他字符串的字符串
【发布时间】:2015-01-14 21:05:19
【问题描述】:

您的建议将不胜感激..... 我的问题是,假设我的 UITEXTVIEW 中有这句话 “我想锻炼身体是为了身体健康,因为工作是让你身体健康的最好方式,工作也能让你在工作中做到最好。”

现在我想删除文字作品 在第一行第 4 个单词中随机而不是静态地那么我该怎么做。在删除之后使用 nsarray 和逐字存储在数组中是否很好,但它不起作用。

【问题讨论】:

  • 我只能勉强理解你在说什么,但是如果你真正理解了 Objective-C(以及一般的编程),你想做的事情(在有意义的范围内)会很简单.
  • 阅读NSStringNSMutableString 的文档。有很多方法可以搜索和修改字符串。
  • 我只想这样做,如果我使用 uitextview 中的 stringByreplacingoccurencesofstring 从第二个数组中删除一个单词,则我正在使用多个数组来存储相同的单词并在 UITEXTVIEW 上映射所有数组,这也必须从其他数组中删除同一个词.....这是问题
  • 抱歉,您的描述不清楚。最好使用相关代码更新您的问题。解释你有什么数据,你想对它做什么,以及你得到了什么。越详细越好。
  • 最后我通过使用 nsmutablestring 从你的第一个答案中得到了我的解决方案,非常感谢。你做得很好,祝你好运。

标签: ios objective-c arrays uitextview


【解决方案1】:

好的,这是一个有效的答案,虽然你的问题有点含糊,但我想我得到了你想要的。

因此,困难在于找到单词的索引,然后从中随机选择一个。这意味着我们不能只使用查找和替换,因为我们只想替换一个。

在这个答案中,我首先找到每个出现的索引,然后将这些索引放入一个数组中,然后再随机挑选出来。然后我使用这个索引和单词的长度来查找和替换单词:

NSString * string=[NSString stringWithFormat:@"i want to work out for the sake of good health because work is a best way to make you physically fit and work also makes you able to do your best in your job."];

NSString * word = @"work";

NSMutableArray * indexes = [NSMutableArray new];

NSRange searchRange = NSMakeRange(0, string.length);
NSRange foundRange;

// This function loops through and finds the index of the word
while (searchRange.location < string.length) {

    searchRange.length = string.length - searchRange.location;

    foundRange = [string rangeOfString:word options:nil range:searchRange];

    if (foundRange.location != NSNotFound) {

        // Add the index to the array
        [indexes addObject:[NSNumber numberWithInteger:foundRange.location]];

        // found an occurrence of the substring! do stuff here
        searchRange.location = foundRange.location+foundRange.length;
    } else {
        // no more substring to find
        break;
    }
}

// Calculate the random index we'll use
NSUInteger randomIndex = arc4random() % [indexes count];

NSInteger stringIndex = [indexes[randomIndex] integerValue];

NSUInteger rangeIntStart = stringIndex;
NSUInteger  rangeIntFinish = word.length + 1;

NSString * result = [string stringByReplacingCharactersInRange:NSMakeRange(rangeIntStart, rangeIntFinish) withString:@""];

NSLog(@"%@",result);

希望这对于将来寻找此问题的任何人来说都是一个更完整的答案。

我可以在 cmets 中看到您可能已经找到了答案,如果您随后添加它并回答您的问题或接受另一个回答该问题的答案,以便其他人从您的工作中受益。

p>

【讨论】:

猜你喜欢
  • 2015-12-08
  • 1970-01-01
  • 2013-09-09
  • 2012-08-31
  • 1970-01-01
  • 2017-04-30
  • 2017-05-17
  • 2013-02-01
  • 1970-01-01
相关资源
最近更新 更多