我目前正在阻止作家。
我想要的是有一个排序来检查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 );
}
答案 0 :(得分: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;
}
}
}
}
答案 1 :(得分: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;
}