Objective-C: Randomly replace characters in string

JoshDG

I'd like to have a function that removes a random set of characters from a string and replaces them with '_'. eg. to create a fill in the blanks type of situation. The way I have it now works, but its not smart. Also I don't want to replace spaces with blanks (as you can see in the while loop). Any suggestions on a more efficient way to do this?

blankItem = @"Remove Some Characters";
for(int j=0;j<totalRemove;j++)
{
    replaceLocation=arc4random() % blankItem.length;
    while ([blankItem characterAtIndex:replaceLocation] == '_' || [blankItem characterAtIndex:replaceLocation] == ' ') {
         replaceLocation=arc4random() % blankItem.length;
    }
   blankItem= [blankItem stringByReplacingCharactersInRange:NSMakeRange(replaceLocation, 1) withString:@"_"];
}

My issue is with the for and while loops in terms of efficiency. But, maybe efficiency isn't of the essence in something this small?

Martin R

If the number of characters to remove/replace is small compared to the length of the string, then your solution is good, because the probability of a "collision" in the while-loop is small. You can improve the method by using a single mutable string instead of allocating a new string in each step:

NSString *string = @"Remove Some Characters";
int totalRemove = 5;

NSMutableString *result = [string mutableCopy];
for (int j=0; j < totalRemove; j++) {
    int replaceLocation;
    do {
        replaceLocation = arc4random_uniform((int)[result length]);
    } while ([result characterAtIndex:replaceLocation] == '_' || [result characterAtIndex:replaceLocation] == ' ');
    [result replaceCharactersInRange:NSMakeRange(replaceLocation, 1) withString:@"_"];
}

If the number of characters to remove/replace is about the same magnitude as the length of the string, then a different algorithm might be better.

The following code uses the ideas from Unique random numbers in an integer array in the C programming language to replace characters at random positions with a single loop over all characters of the string.

An additional (first) pass is necessary because of your requirement that space characters are not replaced.

NSString *string = @"Remove Some Characters";
int totalRemove = 5;

// First pass: Determine number of non-space characters:
__block int count = 0;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                              options:NSStringEnumerationByComposedCharacterSequences
                           usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    if (![substring isEqualToString:@" "]) {
        count++;
    }
}];

// Second pass: Replace characters at random positions:
__block int c = count; // Number of remaining non-space characters
__block int r = totalRemove; // Number of remaining characters to replace
NSMutableString *result = [string mutableCopy];
[result enumerateSubstringsInRange:NSMakeRange(0, [result length])
                              options:NSStringEnumerationByComposedCharacterSequences
                           usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
   if (![substring isEqualToString:@" "]) {
       // Replace this character with probability r/c:
       if (arc4random_uniform(c) < r) {
           [result replaceCharactersInRange:substringRange withString:@"_"];
           r--;
           if (r == 0) *stop = YES; // Stop enumeration, nothing more to do.
       }
       c--;
   }
}];

Another advantage of this solution is that it handles surrogate pairs (e.g. Emojis) and composed character sequences correctly, even if these are stores as two separate characters in the string.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

how to replace characters in a string with integers?

분류에서Dev

php string replace with escape characters

분류에서Dev

replace a line that contains a string with special characters

분류에서Dev

Replace a random block of characters in a string in R

분류에서Dev

Convert string to int-objective c

분류에서Dev

Regex for string replace in C#

분류에서Dev

storing string and characters in two dimensional array (C)

분류에서Dev

C++ String->Replace not working as expected

분류에서Dev

String manipulation with regex and nsarray and mutable strings in objective C

분류에서Dev

Converting string with points into decimal number in objective-c

분류에서Dev

Convert Base64 GZipped string Objective-c or Swift

분류에서Dev

Replace from characters with dots

분류에서Dev

java replace duplicate characters

분류에서Dev

Elasticsearch replace special characters

분류에서Dev

Javascript String Replace - RegEx for Non-Alphanumeric Characters Like Backslash, Greater Than, etc

분류에서Dev

replace `_` with `-` in a string

분류에서Dev

How to remove unsafe characters from string for logging in C#

분류에서Dev

Replacing a character in a string (char array) with multiple characters in C

분류에서Dev

Replace special characters or special characters followed by space

분류에서Dev

Replace highlighting characters with something else

분류에서Dev

Replace special characters in specific field

분류에서Dev

Function to find and replace string in char array (streams) c++

분류에서Dev

How to replace non-zero elements randomly with zero?

분류에서Dev

mysql_real_escape_string ()의 Objective-C에 해당하는 함수

분류에서Dev

array of UIImageView in objective c

분류에서Dev

for .. in objective-c

분류에서Dev

Xcode, IOS, OBJECTIVE C

분류에서Dev

Objective C와 Swift

분류에서Dev

Set httpheader in objective C

Related 관련 기사

  1. 1

    how to replace characters in a string with integers?

  2. 2

    php string replace with escape characters

  3. 3

    replace a line that contains a string with special characters

  4. 4

    Replace a random block of characters in a string in R

  5. 5

    Convert string to int-objective c

  6. 6

    Regex for string replace in C#

  7. 7

    storing string and characters in two dimensional array (C)

  8. 8

    C++ String->Replace not working as expected

  9. 9

    String manipulation with regex and nsarray and mutable strings in objective C

  10. 10

    Converting string with points into decimal number in objective-c

  11. 11

    Convert Base64 GZipped string Objective-c or Swift

  12. 12

    Replace from characters with dots

  13. 13

    java replace duplicate characters

  14. 14

    Elasticsearch replace special characters

  15. 15

    Javascript String Replace - RegEx for Non-Alphanumeric Characters Like Backslash, Greater Than, etc

  16. 16

    replace `_` with `-` in a string

  17. 17

    How to remove unsafe characters from string for logging in C#

  18. 18

    Replacing a character in a string (char array) with multiple characters in C

  19. 19

    Replace special characters or special characters followed by space

  20. 20

    Replace highlighting characters with something else

  21. 21

    Replace special characters in specific field

  22. 22

    Function to find and replace string in char array (streams) c++

  23. 23

    How to replace non-zero elements randomly with zero?

  24. 24

    mysql_real_escape_string ()의 Objective-C에 해당하는 함수

  25. 25

    array of UIImageView in objective c

  26. 26

    for .. in objective-c

  27. 27

    Xcode, IOS, OBJECTIVE C

  28. 28

    Objective C와 Swift

  29. 29

    Set httpheader in objective C

뜨겁다태그

보관