简体   繁体   中英

How do I separate a string with an unknown length?

I'm writing a program that has different outputs depending on a name inputted by the user. The format of the output is decided by the first letter with the rest of the name being used throughout excluding the first letter. Essentially how do I make a substring so it follows something like this?

 Console.WriteLine("What name would you like to use?(please enter in lower case)");
        name = Console.ReadLine();
        namelength = name.Length;
        letter = name.Substring(0);
        restofname = name.Substring(1, namelength);

You can achieve that like this:

Console.WriteLine("What name would you like to use?(please enter in lower case)");
    name = Console.ReadLine();
    letter = name.Substring(0, 1);
    restofname = name.Substring(1);

Hope this helps:

   Console.WriteLine("What name would you like to use?(please enter in lower case)");
    string name = Console.ReadLine();
    string letter = name.Length > 0 ? name.Substring(0, 1): string.Empty;       
    string restofname = string.IsNullOrEmpty(letter) ? string.Empty : name.Substring(1);
    Console.WriteLine(restofname);

String is array of chars, so you can access it using indexes

char letter = name[0];

but you should check if length of string is larger than 0, or is it empty, so your code should look like this

if(!string.IsNullOrEmpty(name) && name.Length>1)
{
   char letter = name[0];
   ......   
}

I have used name.Length > 1 because if name is 1 char than you don't have rest of the name, or second part, and second part can be get like

string restofname = name.Substring(1, name.Length);

if you get rest of name like above then you don't have to introduce extra variable, it's easier to maintain. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM