Split string into array then loop, in C#

23,826

Solution 1

in your case i is not a number, it's the actual element in the array. A foreach loop has no iteration variable, you only have access to the actual element being iterated through i.

So first loop itareation i is Sentence number one, then Sentence number two.

If you want the number, you have to use a for loop instead.

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.

Solution 2

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[]). In the foreach 'i' will be the value of the sentence, so you can concatenate it or process it or do whatever :)

If I've misunderstood, my apologies. I hope that helps :)

Solution 3

In your sample code foreach (string i in arrItemsPlanner) 'i' will get the string value of arrItemsPlanner one by one. For exmaple on first iteration it will have 'Sentence number one' which is obviously not a vlid ont, hence your conversion failed.

Solution 4

Example from 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);
    }

Solution 5

Do you need to trim your string before converting to a number? if thats not you may want to use Int32.tryParse()

Share:
23,826
Dan
Author by

Dan

Updated on January 05, 2020

Comments

  • Dan
    Dan over 4 years

    I have Googled this a LOT but my C# skills are pretty terrible and I just can't see why this isn't working.

    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. e.g.:

    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); 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!

    • Amar Palsapure
      Amar Palsapure over 12 years
      Can you provide some sample of your session string? Try trim Convert.ToInt32(i.Trim()).
    • Shadow The Kid Wizard
      Shadow The Kid Wizard over 12 years
      Post sample value for itemsPlanner - is it something like 1______6______1?
    • Mark Byers
      Mark Byers over 12 years
      If your input string was 324534______1162______12432 instead of "sentences" then your question would make more sense. Also, why are you converting to an integer then back to a string? What are you trying to do?
    • ediblecode
      ediblecode over 12 years
      What type is newItemsPlanner?