0

我现在有作家的障碍。

我想要的是有一个排序来检查 newWord 是否等于 wordInput,如果不等于,它将继续交换字母直到它完成。例如,假设 wordInput 是便便而 newWord 是 oopp,我希望 newWord 最终变成便便,那么我该如何交换呢?

这是我到目前为止的代码。

#include<stdio.h>
#include<string.h>

int main(){
    char wordInput[25];
    char newWord[25];
    char tmp;
    int len;
    int a, b;

    wordInput = "poop";
    newWord = "oopp";

    len = strlen( newWord );

    // Sort back to wordInput
    for( a = 1; a < len; a++ ){
        for( b = 0; b < len - a; b++ ){
            if( newWord[b] != wordInput[b] ){
                tmp = newWord[b];
                newWord[b] = newWord[b + 1];
                newWord[b + 1 ] = tmp;
            }
        }
    }
    printf( "Back to original input: %s\n", newWord );
}
4

2 回答 2

1
#include <stdio.h>
#include <string.h>

void swap(char *a, char *b){
    char wk = *a;
    *a = *b;
    *b = wk;
}

int main(void){
    char wordInput[25];
    char newWord[25];
    int i, len;
    char *p;

    strcpy(wordInput, "poop");
    strcpy(newWord, "oopp");

    len = strlen( newWord );//assert(strlen(newWord)==strlen(wordInput))

    printf("newWold:%s\n",newWord);
    for(i = 0; i < len; ++i ){
        if(wordInput[i] == newWord[i])
            continue;
        if(NULL!=(p=strchr(&newWord[i+1], wordInput[i])))
            swap(&newWord[i], p);
        else
            break;
    }
    if(i < len){
        printf("can't...orz\n");
    } else {
        printf( "Back to original input: %s\n", newWord );
    }
    return 0;
}
于 2013-07-13T00:49:02.070 回答
1

好的,所以基本上你想将一个排序的字母数组转换为一个特定的(随机的?)排序并记录一路上的交换,对吧?

这是执行此操作的一种方法。

#define SWAP(a,b) a^=b;b^=a;a^=b

int main(int argc, char* argv[]) {
  char* wordInput=argv[1];
  char* newWord = (char*)malloc((strlen(wordInput) + 1) * (sizeof(char)));

  int i,j,k;
  fprintf(stdout, "Word is %s\n", wordInput);
  // Sort wordInput into newWord.
  for (i=0; i<strlen(wordInput); i++) {
    // Put this one at the end.
    newWord[i]=wordInput[i];
    // Start at the back of the string, and move it forward if it is less.
    for (j=i-1; j>=0; j--) {
      if (newWord[j+1] < newWord[j]) {
      SWAP(newWord[j+1], newWord[j]);
      } else {
        break;
      }
    }
  }
  newWord[strlen(wordInput)]='\0';

  fprintf(stdout, "Converting sorted word %s back to %s...\n", newWord, wordInput);
  // Recover the original word making swaps.
  for (i=0; i<strlen(wordInput)-1; i++) {
    // Locate this letter in the newWord.
    for (j=i; j<strlen(newWord); j++) {
      if (newWord[j]==wordInput[i]) {
        // Move this letter to the front if it isn't already there.
        if (i != j) {
          SWAP(newWord[j], newWord[i]);
          fprintf(stdout, "Swapping %d with %d --> %s\n", i, j, newWord);
        }
        break;
      }
    }
  } 
}
于 2013-07-12T13:01:51.110 回答