以下是我目前正在執行的示例代碼。如果小於初始值,則動態填充數組
string stringWithDelimiters = "Hello%there%people%of%the%world";
string[] vals = new string[30];
vals = stringWithDelimiters.Split('%');
從上面的代碼中,vals
長度將6.但有以「力」的陣列,以由其它變量的值設定爲即使它是一個空字符串使用所有30的方式少於30?
以下是我目前正在執行的示例代碼。如果小於初始值,則動態填充數組
string stringWithDelimiters = "Hello%there%people%of%the%world";
string[] vals = new string[30];
vals = stringWithDelimiters.Split('%');
從上面的代碼中,vals
長度將6.但有以「力」的陣列,以由其它變量的值設定爲即使它是一個空字符串使用所有30的方式少於30?
stringWithDelimiters.Split('%')
返回一個數組。如果直接在vals
中指定它,它將替換您之前創建的整個數組。
爲了保持您的數組,您必須將由Split
方法返回的數組中的每個值插入到您的vals
數組中。
嘗試:
string stringWithDelimiters = "Hello%there%people%of%the%world";
string[] vals = new string[30];
for (int i = 0; i < vals.Length; i++)
vals[i] = string.Empty;
var tmp = stringWithDelimiters.Split('%');
for (int i = 0; i < tmp.Length; i++)
vals[i] = tmp[i];
我剛剛發現最快的解決了這一點。 (我將使用@ X.L.Ant的解決方案)
tmp.CopyTo(vals, 0);
謝謝你們!我會給他一個答案。 :)
這樣數組vals將始終有30個元素。首先用30個空字符串填充數組,然後用分割的數據填充它。我希望這對你有所幫助。
string stringWithDelimiters = "Hello%there%people%of%the%world";
string[] vals = new string[30];
string[] vals1 = new string[30];
vals1 = stringWithDelimiters.Split('%');
int valslength = vals1.Length;
for (int k = 0; k < 30; k++)
{
vals[k] = "";
}
for (int m = 0; m < valslength; m++)
{
vals[m] = vals1[m];
}
Array.Copy
通常是移動從一個陣列到另一個元件的最快方式。該解決方案將複製拆分數組到30長度數組,然後用空字符串填充其餘(如果有的話)。同時考慮到分割陣列的長度可能超過30(或者任何長度)。
private static string[] GetFixedLengthSplitArray(string input)
{
const int TargetLength = 30;
string[] splitResult = input.Split('%');
string[] values = new string[TargetLength];
Array.Copy(splitResult, 0, values, 0, Math.Min(splitResult.Length, values.Length));
for (int i = splitResult.Length; i < values.Length; i++)
{
values[i] = string.Empty;
}
return values;
}
試過這個,但在's = string.Empty;'中出錯了。 – Musikero31
我剛剛找到最快的方法。但謝謝你的回答。 :) – Musikero31
你說得對。如上所述,它仍然會在內部執行一個循環,但它更清晰。沒想到這種方法。一定很累吧: –