Converting NSString to array of chars inside For L

2019-08-22 02:01发布

问题:

I'm trying to use an existing piece of code in an iOS project to alphabetize a list of words in an array (for instance, to make tomato into amoott, or stack into ackst). The code seems to work if I run it on its own, but I'm trying to integrate it into my existing app.

Each word I want it to alphabetize is stored as an NSString inside an array. The issue seems to be that the code takes the word as an array of chars, and I can't get my NSStrings into that format.

If I use string = [currentWord UTFString], I get an error of Array type char[128] is not assignable, and if I try to create the char array inside the loop (const char *string = [curentWord UTF8String]) I get warnings relating to Initializing char with type const char discards qualifiers. Not quite sure how I can get around it – any tips? The method is below, I'll take care of storing the alphabetized versions later.

- (void) alphabetizeWord {
    char string[128], temp;
    int n, i, j;

    for (NSString* currentWord in wordsList) {
        n = [currentWord length];
        for (i = 0; i < n-1; i++) {
            for (j = i+1; j < n; j++) {
                if (string[i] > string[j]) {
                    temp = string[i];
                    string[i] = string[j];
                    string[j] = temp;
                }
            }
        }
        NSLog(@"The word %@ in alphabetical order is %s", currentWord, string);
    }
}

回答1:

This should work :

- (void)alphabetizeWord {
  char str[128];

  for (NSString *currentWord in wordList)
  {
    int wordLength = [currentWord length];
    for (int i = 0; i < wordLength; i++)
    {
      str[i] = [currentWord characterAtIndex:i];
    }
    // Adding the termination char
    str[wordLength] = 0;
    // Add your word
  }
}

EDIT : Sorry, didn't fully understand at first. Gonna check this out.