生成下长度为N C语言中的所有字符串 [英] Generate all strings under length N in C

查看:191
本文介绍了生成下长度为N C语言中的所有字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编码这个自己和可怕的失败。这基本上是我想要的:

I tried coding this myself and horribly failed. This is basically what I want:

a
b
...
z
aa
ba
...
za
ab
bb
...
zz
aaa
baa
...
zzz

在结束它应该产生的每个字符串,它是那么短的N个字符与字符集AZ。所以我不是在寻找的排列(其中1001实现可以在互联网上找到),但对于组合,带替换(至少这是它被称为在Python) 。 顺序并不重要,速度。

In the end it should have generated every string that is shorter then N characters with charset a-z. So I'm not looking for permutations (of which 1001 implementations can be found on the internet), but for combinations with replacement (at least that's how it's called in Python). Order is not important, speed is.

推荐答案

看起来像你想在C,这里是一个办法做到这一点:

Looks like you want it in C, here is a way to do it:

#include <stdlib.h>
#include <stdio.h>

int inc(char *c){
    if(c[0]==0) return 0;
    if(c[0]=='z'){
        c[0]='a';
        return inc(c+sizeof(char));
    }   
    c[0]++;
    return 1;
}

int main(void){
    int n = 3;
    int i,j;
    char *c = malloc((n+1)*sizeof(char));
    for(i=1;i<=n;i++){
        for(j=0;j<i;j++) c[j]='a';
        c[i]=0;
        do {
            printf("%s\n",c);
        } while(inc(c));
    }
    free(c);
}

这篇关于生成下长度为N C语言中的所有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆