有沒有辦法將每2個字符存儲在一個字符串中?如何在c中存儲每2個字符#
例如
1 + 2-3-2-3 +
因此,這將是 「1+」, 「2-」, 「3-」, 「2-」, 「3+」 作爲單獨的字符串或在一個數組中。
有沒有辦法將每2個字符存儲在一個字符串中?如何在c中存儲每2個字符#
例如
1 + 2-3-2-3 +
因此,這將是 「1+」, 「2-」, 「3-」, 「2-」, 「3+」 作爲單獨的字符串或在一個數組中。
最簡單的方法是走你的字符串循環,並從當前位置需要兩個字符的字符串:
var res = new List<string>();
for (int i = 0 ; i < str.Length ; i += 2)
res.Add(str.Substring(i, 2));
一種先進的解決方案會做LINQ同樣的事情,避免明確循環:
var res = Enumerable
.Range(0, str.Length/2)
.Select(i => str.Substring(2*i, 2))
.ToList();
第二個解決方案是較爲緊湊,但它是很難理解的,至少別人不密切熟悉LINQ。
+1。危險(正則表達式可以快速變得不可讀),但是卻是最不同的方法。 – 2013-03-26 02:28:57
使用for循環,並使用string.Substring()方法提取字符,確保不會超過字符串的長度。
例如
string x = "1+2-3-2-3+";
const int LENGTH_OF_SPLIT = 2;
for(int i = 0; i < x.Length(); i += LENGTH_OF_SPLIT)
{
string temp = null; // temporary storage, that will contain the characters
// if index (i) + the length of the split is less than the
// length of the string, then we will go out of bounds (i.e.
// there is more characters to extract)
if((LENGTH_OF_SPLIT + i) < x.Length())
{
temp = x.Substring(i, LENGTH_OF_SPLIT);
}
// otherwise, we'll break out of the loop
// or just extract the rest of the string, or do something else
else
{
// you can possibly just make temp equal to the rest of the characters
// i.e.
// temp = x.Substring(i);
break; // break out of the loop, since we're over the length of the string
}
// use temp
// e.g.
// Print it out, or put it in a list
// Console.WriteLine(temp);
}
什麼編程語言? – Patashu 2013-03-26 01:39:02
請顯示您嘗試過的代碼並遇到問題。 – 2013-03-26 01:41:52
嗯,通過字符串循環並將每個子字符串副本移動到數組?如果這是您首次引入C#,那麼有大量的在線資源和書籍。我會從那裏開始。 – OldProgrammer 2013-03-26 01:42:12