C语言中的字符串

0 c

如果输出是这样的话,如何用C语言编写代码呢?我需要代码的字符串格式,因为我们的主题是字符串.

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

void main() 
{ 
    char my_string[50];

    printf("Enter a word:");
    scanf("%s", my_string);

    printf("Enter a word:");
    scanf("%s", my_string);

    // Some unknown code here...
    // this part is my only problem to solve this.

    getch();
}
Run Code Online (Sandbox Code Playgroud)

输出:

Hello -> (user input)

World -> (user input)

HWeolrllod -> (result)
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 9

好的,你需要做一些调查.作为一般规则,我们不会为他们做家庭作业,因为:

  • 这是作弊.
  • 如果你逐字复制,你可能会被抓住.
  • 从长远来看,它对你没有帮助.

您应该使用的C库调用用户输入fgets,沿着以下行:

char buffer[100];
fgets (buffer, sizeof(buffer), stdin);
Run Code Online (Sandbox Code Playgroud)

这会将一个字符串输入到名为buffer的字符数组中.

如果你使用两个不同的缓冲区,那么你将拥有内存中的字符串.

然后你需要创建指向它们的指针并遍历输出交替字符的两个字符串.指针不是一个简单的主题,但以下伪代码可能会有所帮助:

set p1 to address of first character in string s1
set p1 to address of first character in string s1
while contents of p1 are not end of string marker:
    output contents of p1
    add 1 to p1 (move to next character)
    if contents of p2 are not end of string marker:
        output contents of p2
        add 1 to p2 (move to next character)
while contents of p2 are not end of string marker:
    output contents of p2
    add 1 to p2 (move to next character)
Run Code Online (Sandbox Code Playgroud)

将其转换为C将需要一些工作,但算法是可靠的.你只需要知道一个字符指针可以定义char *p1;,获取它的内容完成*p1并推进它是p = p + 1;p1++;.

没有为你编写代码(我打算这样做),你可能没有其他需要的东西.