Forum guidelines
AuthorQuestion
splitting a text
Posted on: 22 Nov 2012
Hello
There,

How can one separate a text into 2 columns (FirstName and LastName).
The only Hint I have is the UpperCase of the second name.
Eg. EdwardJohn I want it to be Edward in one column and John in the second column.
Any help shall be appreciated

AuthorReply
Re: splitting a text
Posted on: 22 Nov 2012  
In principle, you can split it using code such as this:

      string name = "EdwardJohn";
      int index = 0;
      for(int i = 1; i < name.Length; i++)
      { 
         if (Char.IsUpper(name[i]))
         { 
            index = i;
            break;
         }
      }
      string firstName = name.Substring(0, index);
      string lastName = name.Substring(index);

Re: splitting a text
Posted on: 22 Nov 2012  
        private void button1_Click(object sender, EventArgs e)
        {
            string sName = "StevePotts";

            StringBuilder sb = new StringBuilder();
            foreach (char c in sName)
            {
                if (Char.IsUpper(c) && sb.Length > 0) sb.Append(' ');
                sb.Append(c);
            }
            sName = sb.ToString();

            textBox1.Text = sName;
        }

Re: splitting a text
Posted on: 22 Nov 2012  
actually i just read it properly, how about something like this.. you could then use firstname and lastname as you want :)

            string sName = "StevePotts";

            StringBuilder sb = new StringBuilder();

            
            foreach (char c in sName)
            {
                if (Char.IsUpper(c) && sb.Length > 0) sb.Append(':');
                sb.Append(c);
            }
            sName = sb.ToString();
            var fullName = sName.Split(':');
            string firstName = fullName[0];
            string lastName = fullName[1];
                       

            textBox1.Text = firstName + " " + lastName;
        }

Re: splitting a text
Posted on: 22 Nov 2012  
Use this code..........      
 TextBox1.Text.Split();
        string fName = string.Empty;
        string lName = string.Empty;
        string[] words = TextBox1.Text.Split(' ');
        if (words.Length >= 3)
        {
            fName = words[0];
          
            lName = words[1];
        }
        else
        {
            fName = words[0];
        }
        TextBoxF.Text = fName.ToString();
        TextBoxL.Text = lName.ToString();......
output display
TextBoxF.Text=Edward and TextBoxL.Text=John
and then write insert query from database , seperate column save the name
Easy method

Re: splitting a text
Posted on: 22 Nov 2012  
Thx Steve,

Seems to work fine with one values.
But one more thing. data to be split is a big table in sql. How to read it, split it into 2 columns and insert new values in another table with 2 columns i.e First name and LastName.
I am thinking of reading data by datareader to put these values in arrays and insert values in new table using sql command. But how???


Re: splitting a text
Posted on: 22 Nov 2012  
is the database mysql, or mssql ? or?
Re: splitting a text
Posted on: 22 Nov 2012  
i dont use ms SQL, but here is some code with how i would get the results back from mysql and add them to a combobox(taken from one of my apps), note you can download the required mysql dll from their site if you are using mysql. this should help


            string MyConString = "SERVER=192.168.0.1;" +
                "DATABASE=userdatabase;" +
                "UID=root;" +
                "PASSWORD=password;";
            
            MySqlConnection connection = new MySqlConnection(MyConString);
            
            string command = "select firstname,lastname from usertable"; // Return the Names
            
            MySqlDataAdapter da = new MySqlDataAdapter(command, connection);
            
            DataTable dt = new DataTable();
            
            da.Fill(dt);

            // Fill the contact list dropdown

            foreach (DataRow row in dt.Rows)
            {
                string rows = string.Format("{0}:{1}", row.ItemArray[0], row.ItemArray[1]);
                
                comboBox1.Items.Add(rows);
            }
            connection.Close();

Re: splitting a text
Posted on: 22 Nov 2012  
just tested this, if you are doing as i said above, then you can use something like this, if you create a textbox set its property to multiline, this adds each row to a new line.          


foreach (DataRow row in dt.Rows)
            {
          string rows = string.Format("{0} {1}", row.ItemArray[0], row.ItemArray[1])+ "\n";
                textBox1.AppendText(rows.ToString());

               
            }
            connection.Close();

Re: splitting a text
Posted on: 22 Nov 2012  
thx Steve,

It is working fine. Along the way I came across another issue where names are like in this format;

STEVEPotts


where all FirstName characters are in uppercase and only the first character of the last name is in uppercase.

How to split such text; I want FirstName STEVE Lastname Potts.
Thanks again

Re: splitting a text
Posted on: 22 Nov 2012  
OOo, im not 100% sure on this, i guess you need to figure a way to Leave the last capital as is, and change the rest to lowercase except the starting letter, i dont know if anyone has better idea, but maybe use a regex to figure this out..

http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

Re: splitting a text
Posted on: 22 Nov 2012  
You can do both just by removing the 'break' statement from my earlier effort:

using System;

class Test
{
   static void Main()
   {
      string[] names = {"EdwardJohn", "STEVEPotts"};
      foreach(string name in names)
      {
        int index = 0;
        for(int i = 1; i < name.Length; i++)
        { 
           if (Char.IsUpper(name[i]))
           { 
              index = i;
           }
        }
        string firstName = name.Substring(0, index);
        string lastName =  name.Substring(index);
        Console.WriteLine("{0} {1}", firstName, lastName);
      }

      Console.ReadKey(); 
   }
}

The output is:

Edward John
STEVE Potts



Re: splitting a text
Posted on: 22 Nov 2012  
Thx for yr prompt response.
 I think of using a loop and extract all uppercase characters except
the last one. Make this part as Firstname and the remaining part of course shall be the lastname.
Any idea how to do this?

Re: splitting a text
Posted on: 22 Nov 2012  
Thx Vulpes,


I think the last challenge I have is to convert object values from the table
retrived by sqldatareader into a string array.

You have used a string array values to split firstname and lastname. I need to convert my values from a database to string array and pass them through the loop as you indicated.

Please any Idea?

Thx in advance.

Re: splitting a text
Posted on: 22 Nov 2012  
I'd use a List rather than an array as you don't know in advance how many records there are to read.

Assuming that column 0 contains the Name field, the code for that will be something like this:

        List<string> names = new List<string>();

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
               if(!reader.IsDBNull)
                  names.Add(reader.GetString(0));
               else
                  names.Add(""); // use empty string if null in database, say
            }

            reader.Close();
        }

        foreach(string name in names)
        {
            string firstName = "";
            string lastName = "";
            if (name != "")
            { 
               int index = 0;
               for(int i = 1; i < name.Length; i++)
               { 
                  if (Char.IsUpper(name[i]))
                  { 
                    index = i;
                  }
               }
               firstName = name.Substring(0, index);
               lastName =  name.Substring(index);
               // add code to insert into new table
             }
         }


Re: splitting a text
Posted on: 23 Nov 2012  
Thx a lot Vulpes,

After days of trying this. You finally showed how to do it.You are a really talented fellow
Thx indeed

Re: splitting a text
Posted on: 21 Dec 2012  
string Name = "EdwardJohn"; string indexes = ""; for (int i = 0; i < Name.ToCharArray().Length;i++ ) { if (Char.IsUpper(Name[i])) { indexes = indexes+ i+"-"; } } if (indexes.Split('-').Length > 1) { int startIndex=Convert.ToInt32(indexes.Split('-')[0]); int Length=Convert.ToInt32(indexes.Split('-')[1].ToString()); string FirstName = Name.Substring(startIndex,Length ); string LastName = Name.Substring(Length); }
Employers - Post Free Jobs

SPONSORED BY

Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.