简体   繁体   English

如何将字符从一个字符串复制到另一个字符串?

[英]How do I copy characters from one string to another string?

I have a problem, I am programming in C and it turns out that I am copying some characters from one string to another but I do it manually, you know with a function that it creates, but I want to know if there is any standard C function that allows me to do that, I will put An example so you can understand what I'm trying to say:我有一个问题,我在 C 中编程,结果发现我正在将一些字符从一个字符串复制到另一个字符串,但我手动完成,你知道它创建的 function,但我想知道是否有任何标准C function 允许我这样做,我会举一个例子,这样你就可以理解我想说的是什么:

char str1[] = "123copy321";
char str2[5];

theFunctionINeed(str1, str2, 3, 6);   //Copy from str1[3] to str1[6]

printf("%s\n", str1);
printf("%s\n", str2);

and the result would be:结果将是:

123copy321
copy

I hope you can help me, thank you我希望你能帮助我,谢谢

You can use pointer arithmetic and the function memcpy :您可以使用指针算法和 function memcpy

#include <stdio.h>
#include <string.h>

int main( void )
{
    char str1[] = "123copy321";
    char str2[5];

    //copy str1[3] up to and including str1[6] to str2
    memcpy( str2, str1 + 3, 4 );

    //add terminating null character to str2
    str2[4] = '\0';

    printf( "%s\n", str1 );
    printf( "%s\n", str2 );
}

This program has the following output:该程序具有以下 output:

123copy321
copy

With theFunctionINeed(str1, str2, 3, 6);使用theFunctionINeed(str1, str2, 3, 6); there are a number of issues:有很多问题:

  1. Source string may be less than 3.源字符串可能少于 3 个。

  2. Available sub-string length may be less than 4.可用的子字符串长度可能小于 4。

  3. Destination array may be too small.目标数组可能太小。

  4. Unusual to pass in the first and last index to copy.不寻常地传入第一个和最后一个索引来复制。 This prevents forming a zero-length sub-string.这可以防止形成零长度的子串。 More idiomatic to pass in beginning and 1) length or 2) index of one-past.更习惯于在开头和 1) 长度或 2) 过去的索引中传递。

  5. How about returning something useful, like was the destination big enough?返回一些有用的东西怎么样,比如目的地足够大?

Alternative untested sample code follows.替代的未经测试的示例代码如下。 restrict means the two pointers should not point to overlapping memory. restrict意味着两个指针不应指向重叠的 memory。

#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

// Return `destination` when large enough
// otherwise return NULL when `size` was too small. 
bool SubString(size_t destination_size, char *restrict destination,
    const char *restrict source, size_t offset, size_t length) {
  if (destination_size == 0) {
    return NULL;
  }
  destination[0] = '\0';

  // Quickly search for the null character among the first `offset` characters of the source.
  if (memchr(source, '\0', offset)) {
    return destination;
  }

  destination_size--;
  size_t destination_length = length <= destination_size ? length : destination_size;
  strncat(destination, source + offset, destination_length);
  return length <= destination_size ? destination : NULL;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM