How to use Substring method to separate key value pairs from array of strings in C#

1 Answer

0 votes
using System;
  
class Program
{
    static void Main()
    {
        String[] keyval = { "Name=Arthur", "Age=157", "Enducation=Hogwarts", "Location=Scotland" };
        
        foreach (var pair in keyval) {
            int position = pair.IndexOf("=");
            if (position < 0) {
                continue;
            }
            Console.WriteLine("Key:{0} - Value:{1}", 
                                pair.Substring(0, position),
                                pair.Substring(position + 1));
        }                          
    }
}
  
  
  
  
/*
run: 
  
Key:Name - Value:Arthur
Key:Age - Value:157
Key:Enducation - Value:Hogwarts
Key:Location - Value:Scotland
  
*/

 



answered Aug 8, 2023 by avibootz
...