C#从字符串中提取固定步长的子字符串

C#的Substring方法只能提取固定长度的子字符串,不能直接提取固定步长的子字符串。因此,我们需要自己编写一个方法来实现这个功能。

这个方法可以用于从字符串中提取固定步长的子字符串。例如,如果 str 是 "HelloWorld",finger 是 2,step 是 3,那么返回的数组将是 ["llo", "rld"]。

注意:
最后的子字符串可能小于步长,这里是保留存入字符串数组中的。
例如,如果 str 是 "HelloWorld",finger 是 0,step 是 3,那么返回的数组将是 ["He", "loW","orl","d"]。

使用重载方法时,可以指定起始位置和结束位置来提取子字符串。例如,如果 str 是 "HelloWorld",startIndex 是 2,endIndex 是 9,step 是 3,那么返回的数组将是 ["llo", "rld"]。

这个方法非常灵活,可以根据需要提取字符串的任意部分。例如,如果 str 是 "HelloWorld",startIndex 是 1,endIndex 是 8,step 是 2,那么返回的数组将是 ["el", "oW", "r"]。

使用该方法时,需要注意以下几点:

  • 步长必须是正数,否则会抛出异常。
  • 结束位置不能超过字符串的长度,否则会抛出异常。
  • 起始位置必须小于结束位置,否则返回一个空数组。
// 定义一个静态方法,接受一个字符串 str、一个整数 finger 和一个整数 step 作为参数
public static string[] StepSubstring(string str, int finger, int step)
{  
    // 计算从 finger 到字符串末尾的长度
    int len = str.Length - finger;  

    // 计算要提取的子字符串的数量。如果 len 可以被 step 整除,则子字符串的数量是 len / step,否则是 len / step + 1。
    int length = len % step == 0 ? len / step : len / step + 1;  

    // 创建一个字符串数组,用于存储提取的子字符串
    string[] substrings = new string[length];  

    // 使用 for 循环来提取子字符串并存储在 substrings 数组中
    for (int i = 0; i < length; i++)  
    {  
        // 计算当前子字符串的长度。如果 i 小于 length - 1 并且 finger + step 不超过字符串的长度,则子字符串的长度为 step,否则为 str.Length - finger。
        int substringLength = (i < length - 1 && finger + step <= str.Length) ? step : str.Length - finger;  

        // 使用 Substring 方法提取子字符串,并将其存储在 substrings 数组中的当前位置
        substrings[i] = str.Substring(finger, substringLength);  

        // 更新 finger 的值,以便下次迭代时提取下一个子字符串
        finger += step;  
    }  

    // 返回存储了所有提取的子字符串的数组
    return substrings;  
}

// 可以指定结束位置的重载方法
public static string[] StepSubstring(string str, int startIndex, int endIndex, int step)
{
    // 检查步长是否为正数
    if (step <= 0)
        throw new ArgumentException("Step must be a positive integer.", nameof(step));

    // 检查结束位置是否超过字符串长度
    if (endIndex > str.Length - 1)
        throw new ArgumentException("EndIndex cannot exceed the string length.", nameof(endIndex));

    // 检查起始位置是否大于等于结束位置
    if (startIndex >= endIndex)
        return Array.Empty<string>();

    // 计算要提取的子字符串的数量。如果 len 可以被 step 整除,则子字符串的数量是 len / step,否则是 len / step + 1。
    int len = endIndex - startIndex;
    int length = len % step == 0 ? len / step : len / step + 1;

    // 创建一个字符串数组,用于存储提取的子字符串
    string[] substrings = new string[length];

    // 使用 for 循环来提取子字符串并存储在 substrings 数组中
    for (int i = 0; i < length; i++)
    {
        // 计算当前子字符串的长度。如果 i 小于 length - 1 并且 startIndex + step 不超过 endIndex,则子字符串的长度为 step,否则为 endIndex - startIndex。
        int substringLength = (i < length - 1 && startIndex + step <= endIndex) ? step : endIndex - startIndex;

        // 使用 Substring 方法提取子字符串,并将其存储在 substrings 数组中的当前位置
        substrings[i] = str.Substring(startIndex, substringLength);

        // 更新 startIndex 的值,以便下次迭代时提取下一个子字符串
        startIndex += step;
    }

    // 返回存储了所有提取的子字符串的数组
    return substrings;
}
posted on 2023-12-07 17:30  瞬间moment  阅读(146)  评论(0编辑  收藏  举报