Hi I want to know how to declare an empty string array (an array of strings with null values), because in my application I will split a fullname of a person into 3 string varainles namely firstname, middle_initial, and lastname like below
string fullname=textBox1.Text.ToString();
string[] arr=fullname.Split(' '); // split the string based on white space
string firstname=arr[0];
string middle_initial=arr[1];
string lastname=arr[2];
here in the above case if the name of a person contains only firstname and lastname then It throws the IndexOutOfRangeException for arr[2]. and also arr[0] contains the firstname and arr[1] contains the lastname which is suppose to be a middle_initial. How to overcome this Exception and wrong array element assigning
thanks
Loading

Puran KaushalRank #2,456 · 573 reputationPosted Jun 1, 2009, 6:29 AM EDT
Hi
Check this the default case is best of your use
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string fullname = "Puran test";
string[] arr = fullname.Split(' '); // split the string based on white space
string firstname = null;
string middle_initial = null;
string lastname = null;
switch (arr.Length)
{
case 1:
firstname = arr[0];
middle_initial = null;
lastname = null;
break;
case 2:
firstname = arr[0];
middle_initial = null;
lastname = arr[1];
break;
case 3:
firstname = arr[0];
middle_initial = arr[1];
lastname = arr[2];
break;
default:
firstname = arr[0];
for (int i = 1; i <=arr.Length - 2; i++)
{
middle_initial = middle_initial + arr[i].ToString();
}
lastname = arr[arr.Length-1];
break;
}
Console.WriteLine(firstname);
Console.WriteLine(middle_initial);
Console.WriteLine(lastname);
Console.ReadLine();
}
}
}
Niradhip ChakrabortyRank #429 · 5.8K reputationPosted Jun 1, 2009, 1:34 PM EDT
Or you can go for three textbox. And assign the value to string. Just a simple design change will make your work simple.
sachi vasishta180 reputationPosted Jun 1, 2009, 9:12 PM EDT
for (int i = 1; i <=arr.Length - 2; i++)
{
middle_initial = middle_initial + arr[i].ToString();
}
lastname = arr[arr.Length-1];
break;
thanks
Puran KaushalRank #2,456 · 573 reputationPosted Jun 2, 2009, 1:21 AM EDT
The default statement is if sombody puts "Puran kumar ji Kaushal" then it will club all the middle string as middle name.For test case just change the name string then u will come to know about it.
Regards
Puran Kaushal
raju s8 reputationPosted Nov 9, 2017, 8:24 PM EST