C - 将数组中的 char 字符串排序为等于 char 用户输入

标签 c arrays sorting alphabet

我现在遇到了写作瓶颈。

我想要的是有一个排序来检查 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/

相关文章:

c - 在 C 中使用 API 线程处理文件

objective-c - 如何从 C 函数获取对象的当前实例

arrays - 如何从 Elm 的数组/列表中删除给定索引处的项目?

javascript - 重用共享 Controller 的功能,为每个页面维护单独的状态

android - 在android中删除项目后如何保持数组列表的排序?

c - 为什么在枚举中#define 相同的项目?

c++ - 如何将 int 数组转换为 OpenSSL BIGNUM?

c - 将一维固定数组传递给二维指针函数

php - 过滤嵌套数组 PHP

c++ - 带有自定义比较器的 std::list::sort 出错( ')' 标记之前的预期主表达式)