Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1058655
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T18:03:22+00:00 2026-05-16T18:03:22+00:00

I have written this function which shuffles the contents of a NSString , and

  • 0

I have written this function which shuffles the contents of a NSString, and it seems to work, but every now and then it crashes. This may be a roundabout way, but I put the characters into an array, swap the elements in the array randomly, and then turn the array back into a string.

I’m not sure what I am doing that is unsafe which makes it crash. I thought it was possibly that I am setting finalLettersString = result, but I also tried finalLettersString = [NSString stringWithString:result] and that also crashes. The reason I am confused is because it does not crash every time. I just keep pressing the shuffle button, and sometimes it crashes. Any places I should look?

/* This function shuffles the letters in the string finalLettersString */

-(IBAction)shuffleLetters:(id)sender{
    int length = [finalLettersString length];
    NSMutableArray * letters = [NSMutableArray arrayWithCapacity:length]; 
    NSLog(@"final letters: %@", finalLettersString);
    for(int i = 0; i < length; i++){
        char ch = [finalLettersString characterAtIndex:i];
        NSLog(@"%c", ch);
        NSString * cur = [NSString stringWithFormat:@"%c", ch];
        [letters insertObject:cur atIndex:i];
    }

    NSLog(@"LETTERS:: %@", letters);

    for(int i = length - 1; i >= 0; i--){
        int j = arc4random() % (i + 1);
        //NSLog(@"%d %d", i, j);
        //swap at positions i and j
        NSString * str_i = [letters objectAtIndex:i];
        [letters replaceObjectAtIndex:i withObject:[letters objectAtIndex:j]];
        [letters replaceObjectAtIndex:j withObject:str_i];      
    }
    NSLog(@"NEW SHUFFLED LETTERS %@", letters);

    NSString * result = @"";
    for(int i = 0; i < length; i++){
        result = [result stringByAppendingString:[letters objectAtIndex:i]];
    }

    NSLog(@"Final string: %@", result);
    finalLettersString = result;
    finalLetters.text = finalLettersString;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T18:03:23+00:00Added an answer on May 16, 2026 at 6:03 pm

    It would be better to copy the contents of the string into a temporary buffer of type unichar and shuffle the contents of the buffer, instead of creating lots of little strings.

    NSUInteger length = [finalLettersString length];
    
    if (!length) return; // nothing to shuffle    
    
    unichar *buffer = calloc(length, sizeof (unichar));
    
    [finalLettersString getCharacters:buffer range:NSMakeRange(0, length)];
    
    for(int i = length - 1; i >= 0; i--){
        int j = arc4random() % (i + 1);
        //NSLog(@"%d %d", i, j);
        //swap at positions i and j
        unichar c = buffer[i];
        buffer[i] = buffer[j];
        buffer[j] = c;
    }
    
    NSString *result = [NSString stringWithCharacters:buffer length:length];
    free(buffer);
    
    // caution, autoreleased. Allocate explicitly above or retain below to
    // keep the string.
    finalLettersString = result;
    

    A couple of things you’ll have to watch out for:

    1. Unicode strings can contain composite characters and surrogate pairs. Shuffling these around will most likely result in an invalid string. While surrogate pairs are rare, it is not uncommon to find that the character é is composed of two characters (the base lowercase letter e and the combining acute accent).

    2. For large strings it could cause memory problems because you end up using 3 times as much space as the original string (1× for the original string, 2× for the buffer we use, and 3× for the new string, and then back down to 2× once we free the buffer).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have written my own function, which in C would be declared like this,
I have always written regexes like this <A HREF=([^]*) TARGET=_blank>([^<]*)</A> but I just learned
I have written a function which reads an input buffer of bytes and produces
I have written this short script (which I've stripped away some minor detail for
I have written a simple jQuery.ajax function which loads a user control from the
I have written a function which scans all the files/directory in a given directory
I have written a java annotation that looks like this: @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) // can
This is what I have written: if ((lstProperty[i].PropertyIdentifier as string).CompareTo(Name) == 0) Resharper put
I have written a secure TCP server in .NET. This was basically as simple
I have written a Windows service that spawns a separate process. This process creates

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.