gpt4 book ai didi

c - 了解 C 字符串连接

转载 作者:行者123 更新时间:2023-11-30 15:58:45 25 4
gpt4 key购买 nike

对于 C 中的评估,我必须获取两个包含字符串的文件,以及一个将它们连接在一起的字符串,例如:

如果 file1 包含

Now is the

time for all

good men to

come to the aid of

the party.

文件2包含:

alpha

beta

gamma

然后是输出

scat XX file1 file2

(scat是程序名称)

应该是

Now is theXXalpha

time for allXXbeta

good men toXXgamma

come to the aid ofXX

the party.XX

以及输出

scat XX file2 file1

应该是

alphaXXNow is the

betaXXtime for all

gammaXXgood men to

XXcome to the aid of

XXthe party.

为了理解这一点,我一直在尝试使用字符串连接来尝试手动将字符串连接在一起。

我的问题是(A:如何访问c中文件的各个行?)和B:如果我手动输入:

  char *str1 = "hello";

char *str2 = "world";

如果没有预定义的函数,我如何将这些字符串添加在一起。我最初的想法是使用 for 循环:

 for(str1; *str1 != '\0'; str1++)

if(*str1 == '\0')

*str1++ = *str2++;

我唯一的问题是这不会因内存访问而导致段错误吗?

当我在字符串中遇到“\0”时..如何扩展该字符串?除非我只是将两个字符串复制到新的 char str3[200] 中?

(以上所有内容都是为了尝试帮助我理解字符串和字符串连接的工作原理,如果您能在学习过程中获得任何帮助,我们将不胜感激。)

尤登

最佳答案

我不会为您做这件事,但这里有一些提示/陷阱。

  1. 处理极端情况。如果文件的行数不同怎么办?

  2. 除非您确实必须支持无限行(询问您的教授),否则我建议输入 2048 个字符的缓冲区,输出 5000 个字符的缓冲区(2*2048 + 连接字符串)。

    <
  3. 您需要使用 fgets 读取两个文件的输入缓冲区,然后将它们与 strncat 连接起来。

关于c - 了解 C 字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9555167/

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