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

C#调用string.CopyTo方法报Index and count must refer to a location within the string错误如何处理

错误根因

你遇到的报错是因为String.CopyTo方法的参数传值不符合逻辑,该方法四个参数的定义依次为:

  1. 源字符串的读取起始索引
  2. 目标字符数组
  3. 目标数组的写入起始索引
  4. 要拷贝的字符总数量

你当前的写法source.CopyTo(4, destinationArray, 0, source.Length)存在两个直接触发越界的问题:

  • 要求从源字符串索引4的位置开始读取,但是要拷贝的长度是整个源字符串的长度,以你给出的示例源字符串example_da(长度为10)为例,从索引4开始最多能读取6个字符,你要求读10个,明显超出了源字符串的有效范围,直接触发报错。
  • 写入目标数组的起始位置填了0,会直接覆盖目标字符串的前N个字符,无法实现替换星号占位区的需求,示例目标字符串this_is_*******_的星号起始位置是索引8,需要将写入起始位对应调整。
修正后的实现代码
public static string CopySixChars(string source, string destination)
{
    // 前置参数校验,避免非法输入触发异常
    if (source == null || source.Length < 6)
        throw new ArgumentException("源字符串长度不能小于6", nameof(source));
    int targetStartIndex = destination.IndexOf('*');
    if (destination == null || targetStartIndex < 0 || destination.Length < targetStartIndex + 6)
        throw new ArgumentException("目标字符串不存在星号占位区或长度不足", nameof(destination));

    char[] destinationArray = destination.ToCharArray();
    // 从源字符串起始位读6个字符,写入到目标字符串星号的起始位置
    source.CopyTo(0, destinationArray, targetStartIndex, 6);
    return new string(destinationArray);
}
效果验证

使用你给出的示例参数调用该方法:

  • 输入源字符串:"example_da"
  • 输入目标字符串:"this_is_*******_"
  • 输出结果:"this_is_example_",完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:15:03