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
raju sPosted Nov 10, 2017, 1:24 AM
Puran KaushalPosted Jun 2, 2009, 5:21 AM
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
sachi vasishtaPosted Jun 2, 2009, 1:12 AM
for (int i = 1; i <=arr.Length - 2; i++)
{
middle_initial = middle_initial + arr[i].ToString();
}
lastname = arr[arr.Length-1];
break;
thanks
Niradhip ChakrabortyPosted Jun 1, 2009, 5:34 PM
Or you can go for three textbox. And assign the value to string. Just a simple design change will make your work simple.
Puran KaushalPosted Jun 1, 2009, 10:29 AM
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();
}
}
}