c - 了解 C 字符串连接

标签 c string string-concatenation

对于 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/

相关文章:

c - C的UUID库?

c - 警告 : assignment makes point from integer without cast

python - 排除匹配的字符串 python re.findall

c - 使用 strtol 验证 ANSI C 中的整数输入

c - C 中的段错误 : Infix to Postfix Evaluation

c++ - 线程 : How to calculate precisely the execution time of an algorithm (duration of function) in C or C++?

database - 一段中多个词短语的模糊匹配算法

excel - Microsoft Excel - 如何在使用 CONCATENATE 函数时保持 dd/mm/yyyy 格式?

iphone - Objective-C - 连接由管道分隔的字符串

python - 字符串连接的变体?