简体   繁体   English

C作业-字符串循环替换

[英]C homework - string loops replacements

I know it's a little unorthodox and will probably cost me some downvotes, but since it's due in 1 hour and I have no idea where to begin I thought I'd ask you guys. 我知道这有点不合常规,可能会花掉我一些票,但是由于它是在1小时内到期,而且我不知道从哪里开始,我想我会问你们。

Basically I'm presented with a string that contains placeholders in + form, for example: 基本上,我会看到一个字符串,其中包含+形式的占位符,例如:

1+2+5

I have to create a function to print out all the possibilities of placing different combinations of any given series of digits . 我必须创建一个函数来打印出放置任何给定系列数字的不同组合的所有可能性 Ie for the series: 即该系列:

[9,8,6] // string array

The output will be 输出将是

16265
16285
16295
18265
18285
18295
19265
19285
19295

So for each input I get (number of digits)^(number of placeholders) lines of output. 因此,对于每个输入,我得到(数字位数)^(占位符数量)输出行。 Digits are 0-9 and the maximum form of the digits string is [0,1,2,3,4,5,6,7,8,9] . 数字为0-9,数字字符串的最大形式为[0,1,2,3,4,5,6,7,8,9] The original string can have many placeholders (as you'd expect the output can get VERY lengthly). 原始字符串可以具有许多占位符(如您所期望的那样,输出会很长)。

I have to do it in C, preferably with no recursion. 我必须用C来做,最好不要递归。 Again I really appreciate any help, couldn't be more thankful right now. 再一次,我非常感谢您的帮助,现在不能再多谢了。

If you can offer an idea, a simplified way to look at solving this, even in a different language or recursively, it'd still be ok, I could use a general concept and move on from there. 如果您能提供一种想法,一种简化的方式来解决这个问题,即使使用其他语言或递归,也可以,我可以使用一般概念并从此继续进行。

It prints them in different order, but it does not matter. 它以不同的顺序打印它们,但这没有关系。 and it's not recursive. 而且它不是递归的。

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

int // 0 if no more.
get_string(char* s, const char* spare_chr, int spare_cnt, int comb_num){
    for (; *s; s++){
        if (*s != '+') continue;
        *s = spare_chr[comb_num % spare_cnt];
        comb_num /= spare_cnt;
    };
    return !comb_num;
};

int main(){
    const char* spare_str = "986";
    int num = 0;
    while (1){
        char str[] = "1+2+5";
        if (!get_string(str, spare_str, strlen(spare_str), num++)) 
            break; // done
        printf("str num %2d: %s\n", num, str);
    };
    return 0;
};

In order to do the actual replacement, you can use strchr to find the first occurrence of a character and return a char * pointer to it. 为了进行实际替换,您可以使用strchr查找字符的第一个匹配项并返回一个char *指针。 You can then simply change that pointer's value and bam, you've done a character replacement. 然后,您可以简单地更改该指针的值和bam,完成字符替换。

Because strchr searches for the first occurrence (before a null terminator), you can use it repeatedly for every value you want to replace. 由于strchr搜索第一个匹配项(在空终止符之前),因此可以对要替换的每个值重复使用它。

The loop's a little trickier, but let's see what you make of this. 循环有点棘手,但让我们看看您如何做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM