[英]Split string into array then loop, in C#
我已經在Google上搜索了很多,但是我的C#技能非常糟糕,我看不出為什么這不起作用。
我有一個來自會話對象的字符串,我對設置沒有任何控制。 該字符串包含一些由六個下划線分隔的句子。 例如:
Sentence number one______Sentence number two______Sentence number three etc
我想將此字符串除以六個下划線,並返回結果數組中的每個項目。
這是我的代碼:
string itemsPlanner = HttpContext.Current.Session["itemsPlanner"].ToString();
string[] arrItemsPlanner = itemsPlanner.Split(new string[] { "______" }, StringSplitOptions.None);
foreach (string i in arrItemsPlanner)
{
newItemsPlanner += "debug1: " + i; //This returns what looks like a number, as I'd expect, starting at zero and iterating by one each loop.
int itemNumber;
try
{
itemNumber = Convert.ToInt32(i);
string sentence = arrItemsPlanner[itemNumber].ToString();
}
catch (FormatException e)
{
return "Input string is not a sequence of digits.";
}
catch (OverflowException e)
{
return "The number cannot fit in an Int32.";
}
finally
{
return "Fail!"
}
}
每當我運行此命令時,會話都會成功恢復,但是顯示以下內容的行:itemNumber = Convert.ToInt32(i); 每次都失敗,並且出現錯誤消息“輸入字符串不是數字序列”。
有人可以為此指出正確的方向嗎?
非常感謝!
在你的情況下i
不是一個數字,它是數組中的實際元素。 foreach循環沒有迭代變量,您只能訪問通過i
迭代的實際元素。
因此,第一個循環迭代i是第一句 ,然后是第二句 。
如果需要該數字,則必須使用for循環。
所以像這樣
for( int i = 0; i < arrItemsPlanner.length; i++ ){
//on first iteration here
//i is 0
//and arrItemsPlanner[i] id "Sentence number one"
}
希望能幫助到你。
如果您只想獲取每個句子並對其進行處理,則可以做到這一點:
string itemsPlanner = HttpContext.Current.Session["itemsPlanner"].ToString();
string[] arrItemsPlanner = itemsPlanner.Split("______");
foreach (string i in arrItemsPlanner)
{
// Do something with each sentence
}
您可以拆分字符串以及char(或char [])。 在foreach中,“ i”將是句子的值,因此您可以將其連接或處理或執行任何操作:)
如果我誤解了,我深表歉意。 希望對您有所幫助:)
從您的示例中, i
沒有包含有效的整數,因此Convert.ToInt32
失敗。 foreach
循環使用句子數組中的當前項目設置i
,因此基本上i
總是在您的主字符串中包含一個句子。 如果要讓i
成為數組中的索引,請使用for
循環。
來自MSDN的示例。
string words = "This is a list of words______with a bit of punctuation" +
"______a tab character.";
string [] split = words.Split(new Char [] {'_'}, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in split) {
if (s.Trim() != "")
Console.WriteLine(s);
}
在轉換為數字之前,是否需要修剪字符串? 如果不是這樣,您可能想使用Int32.tryParse()
在您的示例代碼foreach (string i in arrItemsPlanner)
“ i”將一一獲取arrItemsPlanner的字符串值。 例如,在第一個迭代中,它將有“一號句子”,這顯然不是重要的,因此轉換失敗。
i
只包含以下字符串片段number one
: number one
Sentence number two
Sentence number three
和Sentence number three
。 如果您希望它包含表示ht索引的int,請使用:1) for
循環2)在您的foreach
之前定義的int
並在foreach
代碼中將其增加(myInt ++)!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.