如果输出是这样,你如何用 C 语言编写代码?我需要代码的strings 格式,因为我们的主题是strings。
#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();
}
输出:
Hello -> (user input)
World -> (user input)
HWeolrllod -> (result)
最佳答案
好的,你需要做一些调查。作为一般规则,我们不会为人们做家庭作业,因为:
- 这是作弊。
- 如果逐字复制,您可能会被发现。
- 从长远来看,它对您毫无帮助。
您应该使用的用于用户输入的 C 库调用是 fgets
,如下所示:
char buffer[100];
fgets (buffer, sizeof(buffer), stdin);
这会将一个字符串输入到名为 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)
将其转换为 C 语言需要一些工作,但该算法是可靠的。你只需要知道字符指针可以用 char *p1;
定义,获取它的内容是用 *p1
完成的,推进它是 p = p + 1;
或 p1++;
。
除了为您编写代码(我不会会这样做)之外,您可能不需要太多其他东西。
关于c - C语言中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4816819/