AllTheTimeWorld.com

csharp stringsNames: Using String Functions

Names: Using String Functions

Split name into first and last

Names: Using String Functions

Split name into first and last

Start a new project named Names. Build the form as shown below:

  1. There is a labellabel lblInstructions with the words "Enter a name as last,first"
  2. There is a text boxtext box named txtInput.
  3. There is a buttonbutton, btnOK.
  4. There is a labellabel named lblOutput.
  5. Set the accept button for the form to btnOK.

shows form at runtime with Banks,Robin in text and Hello Robin Banks in label

4. Write the code as shown below:

private void btnOK_Click(object sender, EventArgs e)
{
   String s = txtInput.Text;
   // Split name on comma. 
   String[] parts= s.Split(',');
   // parts[0] will be last name, parts[1] will be first name.
   // Set output to "Hello " + first name + " " + last name.
   lblOutput.Text = "Hello " + parts[1] + " " + parts[0];        
}