You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C语言标准函数实现字符串指定区间字符复制?

C标准库中复制字符串指定区间的方法

C标准库中没有直接提供从源字符串指定起始索引到结束索引复制字符到目标数组的专用函数,但可以通过memcpy或strncpy配合指针偏移轻松实现需求,以下是具体方案:

核心实现思路

你的需求是复制str1[3]到str1[6]的字符(共4个字符),关键步骤:

  1. 定位源字符串的起始位置:str1 + 3(指针偏移,直接指向第4个字符)
  2. 计算要复制的字符长度:结束索引 - 起始索引 + 1(因为包含两端索引的字符)
  3. 复制字符后手动添加字符串终止符'\0'(标准库复制函数不会自动添加,确保目标是合法字符串)

用memcpy实现(推荐)

memcpy是最适合该场景的函数,它直接复制指定字节数的内存内容,效率高:

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

int main() {
    char str1[] = "123copy321";
    char str2[5];
    
    const size_t start_idx = 3;
    const size_t end_idx = 6;
    const size_t copy_len = end_idx - start_idx + 1;
    
    // 复制指定区间的字符
    memcpy(str2, str1 + start_idx, copy_len);
    // 手动添加字符串终止符
    str2[copy_len] = '\0';
    
    printf("%s\n", str1);
    printf("%s\n", str2);
    return 0;
}

用strncpy实现

strncpy也可以实现,但需要注意它的行为特性(若源长度不足会补0,足够则不自动加终止符),所以同样要手动添加'\0':

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

int main() {
    char str1[] = "123copy321";
    char str2[5];
    
    const size_t start_idx = 3;
    const size_t end_idx = 6;
    const size_t copy_len = end_idx - start_idx + 1;
    
    strncpy(str2, str1 + start_idx, copy_len);
    str2[copy_len] = '\0';
    
    printf("%s\n", str1);
    printf("%s\n", str2);
    return 0;
}

注意事项

  • 确保目标数组的大小足够:必须能容纳复制的字符数 + 1(终止符),否则会出现缓冲区溢出
  • 验证索引合法性:要保证start_idx和end_idx小于源字符串的长度(strlen(str1)),避免越界访问导致未定义行为

内容的提问来源于stack exchange,提问作者WalterPH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:20:31