gpt4 book ai didi

c - C中的字符串递增函数

转载 作者:行者123 更新时间:2023-12-02 01:27:05 24 4
gpt4 key购买 nike

对于我的编程课,我正在尝试编写一个函数 incrementstring(),它接受从驱动程序传入的字符串“str”,并将其加一。它应该适用于字母和数字(例如,“1”变为“2”,“a”变为“b”,“z”变为“aa”,“ZZ”变为“AAA”)。我几乎所有测试条件都有效,除了一个我似乎无法找到解决方法的错误。

这是我目前拥有的:

void incrementstring(char* str){
int i;
int j;
int length = strlen(str);
for(i = strlen(str)-1; i >= 0; i--){
if (str[i] == '9'){
str[i] = '0';
if (str[0] == '0'){
for (j = strlen(str)-1; j>=0; j--){ //This loop is the problem
str[j+1] = str[j];
}
str[0] = '1';
}
}
else if (str[i] == 'z'){
if (str[0] == 'z'){
str[i] = 'a';
str[i+1] = 'a';
}
str[i] = 'a';
}

else if (str[i] == 'Z'){
if(str[0] == 'Z'){
str[i] = 'A';
str[i+1] = 'A';
}
str[i] = 'a';
}
else{
str[i]++;
return;
}

}
}

当我运行该函数时,驱动程序输出如下:

 1. testing "1"... = 2. Correct!
2. testing "99"... = 100. Correct!
3. testing "a"... = b. Correct!
4. testing "d"... = e. Correct!
5. testing "z"... = INCORRECT: we got "aa0". We should be getting "aa" instead.
6. testing "aa"... = ab. Correct!
7. testing "Az"... = Ba. Correct!
8. testing "zz"... = aaa. Correct!
9. testing "cw"... = cx. Correct!
10. testing "tab"... = tac. Correct!
11. testing "500"... = 501. Correct!

11 tests run.

我在第 9 行写了一个 for 循环来处理 '99' 到 '100' 的情况。它获取字符串的每个索引并将其向右移动一位,然后将“1”添加到字符串的开头。但是,由于某种原因,这个循环弄乱了第 5 个测试条件,如上所示。如果我取消循环,'99' 将变为 '00',但第 5 个测试将毫无问题地通过。我在这里碰壁了,我想知道是否有人可以提供一些见解。

非常感谢您的帮助,谢谢。

最佳答案

同时跟踪字符串长度以确保您不会覆盖其分配的空间,同时向每个 if()if else 添加一个空终止字符 segmentation :

str[0] = '1';
str[1] = 0;

...

str[i] = 'a';
str[i+1] = 0;

等等。

最后的声明可能没有按照您的预期去做。
我相信您想要做的是增加表达式以指向 str 拥有的下一个内存元素。
请记住 str 实际上不是数组。它是一个指针。 [...]
您使用的符号是 C 中提供的一种便利,允许像引用指针这样的数组。
因此,表达式 str[i] 也可以表示为 *(str + i)。如果它是您想要的下一个内存位置(存储下一个 char 的位置),表达式将是:*(str + i++),在使用数组表示法时转换为:str[i++]

更改以下内容

else{
str[i]++;

到:

else{
str[i++]=0;

关于c - C中的字符串递增函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36502306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com