我现在遇到了写作瓶颈。
我想要的是有一个排序来检查 newWord 是否等于 wordInput,如果不等于,它会一直交换字母直到等于。例如,假设 wordInput 是 poop,newWord 是 oopp,我希望 newWord 最终变成 poop,那么我该如何交换呢?
这是我目前的代码。
#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 );
}
最佳答案
#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;
}
关于C - 将数组中的 char 字符串排序为等于 char 用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17615236/