0

I'm writing a program that limits how many characters can be in the output. Essentially a student id assigner and I'm now sure how to count only a specific amount of characters in a string. My code looks like this so far.

 string firstname, middleinitial, lastname,yearofentry;
        int year;
        Console.WriteLine("Please enter your first name.");
        firstname = Console.ReadLine();

        Console.WriteLine("Please enter your middle initial.");
        middleinitial = Console.ReadLine();

        Console.WriteLine("Please enter your last name.");
        lastname = Console.ReadLine();

        Console.WriteLine("Please enter your year of entry.");
        yearofentry = Console.ReadLine();
        year = (Convert.ToInt32(yearofentry)-2000);



        Console.WriteLine(firstname +middleinitial+ lastname + year + "@mail.edu");
    }
}

}

Robert K
  • 19
  • 4
  • 1
    What are the specific limits you want to add? – Nick Bailey Feb 25 '15 at 17:47
  • See http://stackoverflow.com/questions/5557889/console-readline-max-length – Ryan C Feb 25 '15 at 17:48
  • I need to make sure only the first 7 characters of the last name are used and the last two of the year are used – Robert K Feb 25 '15 at 17:48
  • 1
    Only the first 7 characters of the last name? That seems... a bit peculiar. Just as an example, my last name is 9 letters long and really needs those final 2 to work. ;) –  Feb 25 '15 at 17:51
  • 1
    There are different things of what you may want to achieve: 1. Limit the number of chars which can be input at all (needs some direct input control, e.g. a textbox with a length limit); 2. Accept any input but discard some of it (what @reggae suggests); 3. Limit the number of chars which can be in a string class you write (plus deal with too much input in some way) -- that's what your title suggests; 4. Accept and store all input, but limit the *output* (e.g for a formatted tabular printout). I have the feeling you want 4. – Peter - Reinstate Monica Feb 25 '15 at 21:35

1 Answers1

0

Just read in the full string, TrimStart() it and then use Substring() to get the parts you need

Console.WriteLine("Please enter your last name.");
lastname = Console.ReadLine().TrimStart();
var substrLen = Math.Min(lastname.Length, 7);
lastname = lastname.Substring(0, substrLen);

In the last WriteLine() call you can use .ToString("00") to get the 2 digits you require

Console.WriteLine(firstname + middleinitial + lastname + year.ToString("00") + "@mail.edu");

You should check that your users are entering a value between 2000 and 2099 though also.

reggaeguitar
  • 1,795
  • 1
  • 27
  • 48
  • 1
    I think that substring() throws an exception when the string length is too short for the requested substring, cf. https://msdn.microsoft.com/en-us/library/aka44szs%28v=vs.110%29.aspx. Therefore the length of the substring must be limited to the input length. – Peter - Reinstate Monica Feb 25 '15 at 21:30