简体   繁体   English

在C#中将字符串拆分为数组,然后循环

[英]Split string into array then loop, in C#

I have Googled this a LOT but my C# skills are pretty terrible and I just can't see why this isn't working. 我已经在Google上搜索了很多,但是我的C#技能非常糟糕,我看不出为什么这不起作用。

I have a string which comes from a session object, which I don't have any control over setting. 我有一个来自会话对象的字符串,我对设置没有任何控制。 The string contains some sentences separated by six underscores. 该字符串包含一些由六个下划线分隔的句子。 eg: 例如:

Sentence number one______Sentence number two______Sentence number three etc

I want to split this string by the six underscores and return each item in the resultant array. 我想将此字符串除以六个下划线,并返回结果数组中的每个项目。

Here's the code I have: 这是我的代码:

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!"
  }
}

Whenever I run this, the session is being retreived successfully but the line which says: itemNumber = Convert.ToInt32(i); 每当我运行此命令时,会话都会成功恢复,但是显示以下内容的行:itemNumber = Convert.ToInt32(i); fails every time and I get an error saying "Input string is not a sequence of digits." 每次都失败,并且出现错误消息“输入字符串不是数字序列”。

Can anyone point me in the right direction with this please? 有人可以为此指出正确的方向吗?

Many thanks! 非常感谢!

in your case i is not a number, it's the actual element in the array. 在你的情况下i不是一个数字,它是数组中的实际元素。 A foreach loop has no iteration variable, you only have access to the actual element being iterated through i . foreach循环没有迭代变量,您只能访问通过i迭代的实际元素。

So first loop itareation i is Sentence number one , then Sentence number two . 因此,第一个循环迭代i是第一句 ,然后是第二

If you want the number, you have to use a for loop instead. 如果需要该数字,则必须使用for循环。

So something like this 所以像这样

for( int i = 0; i < arrItemsPlanner.length; i++ ){
  //on first iteration here
  //i is 0
  //and arrItemsPlanner[i] id "Sentence number one"
}

Hope it helps. 希望能帮助到你。

If you just want to get each sentence and do something with it, this will do the trick: 如果您只想获取每个句子并对其进行处理,则可以做到这一点:

string itemsPlanner = HttpContext.Current.Session["itemsPlanner"].ToString(); 
string[] arrItemsPlanner = itemsPlanner.Split("______"); 

foreach (string i in arrItemsPlanner) 
{ 
  // Do something with each sentence
}

You can split over a string as well as char (or char[]). 您可以拆分字符串以及char(或char [])。 In the foreach 'i' will be the value of the sentence, so you can concatenate it or process it or do whatever :) 在foreach中,“ i”将是句子的值,因此您可以将其连接或处理或执行任何操作:)

If I've misunderstood, my apologies. 如果我误解了,我深表歉意。 I hope that helps :) 希望对您有所帮助:)

From your example i does not contain a valid integer number, thus Convert.ToInt32 fails. 从您的示例中, i没有包含有效的整数,因此Convert.ToInt32失败。 The foreach loop sets i with the current item in the sentences array, so basically i always contains one of the sentences in your main string. foreach循环使用句子数组中的当前项目设置i ,因此基本上i总是在您的主字符串中包含一个句子。 If you want i to be the index in the array, use a for loop. 如果要让i成为数组中的索引,请使用for循环。

Example from MSDN . 来自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);
    }

Do you need to trim your string before converting to a number? 在转换为数字之前,是否需要修剪字符串? if thats not you may want to use Int32.tryParse() 如果不是这样,您可能想使用Int32.tryParse()

In your sample code foreach (string i in arrItemsPlanner) 'i' will get the string value of arrItemsPlanner one by one. 在您的示例代码foreach (string i in arrItemsPlanner) “ i”将一一获取arrItemsPlanner的字符串值。 For exmaple on first iteration it will have 'Sentence number one' which is obviously not a vlid ont, hence your conversion failed. 例如,在第一个迭代中,它将有“一号句子”,这显然不是重要的,因此转换失败。

i only contains one of the string fragment which will be : number one Sentence number two and Sentence number three . i只包含以下字符串片段number onenumber one Sentence number two Sentence number threeSentence number three If you want it to contain an int representing ht index, use : 1) a for loop 2) an int defined before your foreach and increase it (myInt++) in the foreach code ! 如果您希望它包含表示ht索引的int,请使用:1) for循环2)在您的foreach之前定义的int并在foreach代码中将其增加(myInt ++)!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM