C程序字符串

标签 c string debugging

对于我程序的一部分,我想将两个字符串连接在一起,每个字符之间有一个星号。例如,如果我有第一个字符串 "abcde" 和第二个字符串 "1234567",我想得到 "a* b*c*d*e*1*2*3*4*5*6*7*".

对于程序的这一部分,我有:

char *widen_stars(char *one, char *two)
{

    int length_one = strlength(one); // length of first parameter
    int length_two = strlength(two); // Length of second parameter

    char *p = malloc((sizeof(char) * (length_one + length_two) * 2)+ 1), *p_start; //Allocate enough memory for both strings concatenated together with a * between each letter

    p_start = p;

        while(*one != '0') 
        {
            if( (p - p_start) % 2 == 0) // Keeps track of where we are in the p string
            {
            *p = *one;
            p++;
            one++;
            }
            else
            {
            *p = '*';
            p++;
            }
        }



        while(*two != '0')
        {
            if( (p - p_start) % 2 == 0)
            {
            *p = *two;
            p++;
            two++;
            }
            else
            {
            *p = '*';
            p++;
            }
        }



return p_start;
}

int main(int argc, char *argv[])
{

    char first[31]= {0};
    char second[31]= {0};
    char *f = first, *s = second;

    printf("Please enter a string of maximum 30 characters: ");
    scanf("%s", f);
    printf("Please enter a string of maximum 30 characters: ");
    scanf("%s", s);

    printf("The combined string is: %s\n", widen_stars(f, s));

    }
return 0;
}

但是,当我使用上述输入运行程序时,我得到类似 "a*b*c*d*e*" 的内容,没有任何第二个字符串。如果我在注释中阻止第一个 while 循环以测试第二个循环,我会得到类似 "1*2*3*4*5*5*7*" 的内容,这让我摸不着头脑.

最佳答案

你的问题出在这里:

while(*oneOrTwo != '0')

如果您正在寻找字符串的结尾,您应该寻找的是 '\0',而不是 '0'。前者是字符串结束标记,后者只是字符 0


另外,还有更少的...,错误,冗长方法可以做到这一点(假设这不是类作业 - 如果是,您应该使用当前的方法) .例如:

#include <stdio.h>
#include <string.h>

char *widen_stars(char *one, char *two) {
    // Need to cater for memory exhaustion.

    char *p = malloc((strlen(one) + strlen(two)) * 2) + 1);
    if (p == NULL) return NULL;

    // Init to empty string in case both inputs empty.

    *p = '\0';

    // Save string start for return.

    char *p_start = p;

    // Add character and asterisk for every character in both strings.

    while (*one != '\0') {
        sprintf(p, "%c*", *one++);
        p += 2;
    }

    while (*two != '\0') {
        sprintf(p, "%c*", *two++);
        p += 2;
    }

    // Remove last asterisk (if needed).

    // *(--p) = '\0';

    // Return result.

    return p_start;
}

这基于您的实际预期结果,即在每个字符 后放置一个星号。但是,您的规范要求在每个字符之间 一个星号。如果您决定使用后者,只需取消注释函数中的倒数第二个语句,基本上备份并用字符串结束标记替换最后的星号。

关于C程序字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092746/

相关文章:

linux - 下一个或步骤时 GDB 在微妙的线条上

c - C 中的菜单驱动程序对链表执行各种操作

c - C语言中如何求和?

string - 将整数字符串日期转换为实际日期

python 制作我自己的小写转换器

java - 旅行推销员本地搜索启发式

c - 直接以二进制执行计算机指令

c - 为什么我的程序不能计算字符串中的单词数?

c# - Csharp 子字符串文本并将其添加到列表

visual-studio-2010 - 用于 x64 调试的 SOS 扩展