Programming Fundamentals/Strings/C Sharp

From Wikiversity
Jump to navigation Jump to search

strings.cs[edit | edit source]

// This program splits a given comma-separated name into first and last name
// components and then displays the name.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C_Sharp_Programming

using System;

public class Strings
{
    public static void Main(String[] args)
    {
        string name;
        string first;
        string last;
        
        name = GetName();
        last = GetLast(name);
        first = GetFirst(name);
        DisplayName(first, last);
    }

    private static string GetName()
    {
        string name;
        int index;
    
        do
        {
            Console.WriteLine("Enter name (last, first):");
            name = Console.ReadLine();
            index = name.IndexOf(",");
        } while (index < 0);
        
        return name;
    }

    private static string GetLast(string name)
    {
        string last;
        int index;
    
        index = name.IndexOf(",");
        if(index < 0)
        {
            last = "";
        }
        else
        {
            last = name.Substring(0, index);
        }
        
        return last;
    }

    private static string GetFirst(string name)
    {
        string first;
        int index;
    
        index = name.IndexOf(",");
        if(index < 0)
        {
            first = "";
        }
        else
        {
            first = name.Substring(index + 1, name.Length - index - 1);
            first = first.Trim();
        }
    
        return first;    
    }

    private static void DisplayName(string first, string last)
    {
        Console.WriteLine("Hello " + first + " " + last + "!");
    }
}

Try It[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own C Sharp compiler / interpreter / IDE.

See Also[edit | edit source]