【问题标题】:Concatenate char array and char连接 char 数组和 char
【发布时间】:2017-09-13 19:06:29
【问题描述】:

我是 C 语言的新手。我需要连接 char 数组和一个 char。在 java 中我们可以使用 '+' 操作,但在 C 中这是不允许的。 Strcat 和 strcpy 也不适合我。我怎样才能做到这一点?我的代码如下

void myFunc(char prefix[], struct Tree *root) {
    char tempPrefix[30];
    strcpy(tempPrefix, prefix);
    char label = root->label;
    //I want to concat tempPrefix and label

我的问题与 concatenate char array in C 不同,因为它将 char 数组与另一个连接,但我的问题是带有 char 的 char 数组

【问题讨论】:

标签: c arrays string concatenation


【解决方案1】:

真的很简单。主要关心的是tempPrefix 应该有足够的空间来存放前缀+原始字符。由于 C 字符串必须以 null 结尾,因此您的函数不应复制超过 28 个字符的前缀。它是 30(缓冲区的大小)- 1(根标签字符)-1(终止空字符)。幸运的是标准库有strncpy:

size_t const buffer_size = sizeof tempPrefix; // Only because tempPrefix is declared an array of characters in scope. 
strncpy(tempPrefix, prefix, buffer_size - 3);
tempPrefix[buffer_size - 2] = root->label;
tempPrefix[buffer_size - 1] = '\0';

在函数调用中不要对缓冲区大小进行硬编码也是值得的,这样您就可以通过最少的更改来增加其大小。


如果您的缓冲区不完全适合,则需要更多的跑腿工作。该方法与以前几乎相同,但需要调用strchr 才能完成图片。

size_t const buffer_size = sizeof tempPrefix; // Only because tempPrefix is declared an array of characters in scope. 
strncpy(tempPrefix, prefix, buffer_size - 3);
tempPrefix[buffer_size - 2] = tempPrefix[buffer_size - 1] = '\0';
*strchr(tempPrefix, '\0') = root->label;

我们再次复制不超过 28 个字符。但显式地用 NUL 字节填充结尾。现在,由于strncpy 使用最多为count 的NUL 字节填充缓冲区,以防被复制的字符串更短,实际上复制前缀之后的所有内容现在都是\0。这就是为什么我立即尊重strchr 的结果,它保证指向一个有效的字符。确切地说是第一个可用空间。

【讨论】:

  • 我在这里没有得到预期的输出。我可以看到附加字符位于我的 tempPrefix 字符数组的第 28 个位置,但是当我打印它时,它不存在。我们不应该连接到数组中当前文本的下一个位置,而不是连接到数组的末尾。
  • @GeorgeKlimas - 我的小错误。 strncpy 复制 最多 个字符,包括在内。这意味着需要调整对它的调用。有关详细信息,请参阅我的编辑。
  • 我仍然没有在 char 数组中获得附加字符。调试显示字符被附加到 28 位置。
  • @GeorgeKlimas - 是的,我正在编辑该问题的修复程序,因为我最初误解了您问题的参数。
  • @GeorgeKlimas - NP。很高兴能提供帮助。
【解决方案2】:

strXXX() 系列函数大多对字符串进行操作(搜索相关的除外),因此您将无法直接使用库函数。

您可以找出现有空终止符的位置,将其替换为您要连接的char 值,然后添加空终止符。但是,您需要确保为源留出足够的空间来容纳串联的 字符串

类似的东西(未测试)

#define SIZ 30


//function
char tempPrefix[SIZ] = {0};     //initialize
strcpy(tempPrefix, prefix);    //copy the string
char label = root->label;      //take the char value

if (strlen(tempPrefix) < (SIZ -1))   //Check: Do we have room left?
{
    int res = strchr(tempPrefix, '\0');  // find the current null
    tempPrefix[res] = label;             //replace with the value
    tempPrefix[res + 1] = '\0';          //add a null to next index
}

【讨论】:

  • 我在这里没有得到输出。我可以看到res 正在获得负值。是不是有问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-19
  • 2011-01-14
  • 2014-08-06
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
相关资源
最近更新 更多