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;
}
浙公網安備 33010602011771號