-1

I have a piece of code and I need to shorten a string that I have in a variable. I was wondering how could I do this. My code is below.

string test = Console.ReadLine();
if(string.Length > 5)
{
    //shorten string
}
Console.WriteLine(test);
Console.ReadLine();
Marek
  • 33
  • 1
  • 3
  • 6

3 Answers3

7

Use string.Substring.

test = test.Substring(0, 5);

Substring(0,5) will take the first five characters of the string, so assigning it back will shorten it to that length.

Cyral
  • 13,999
  • 6
  • 50
  • 90
3

Here is how:

test = test.Substring(0,5);

Please note also that your if statement is wrong. It should check the test variable like this:

if(test.Length > 5)
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
1

You are doing the comparation wrong, you must compare with test instead with the property string

string test = Console.ReadLine();
if(test.Length > 5)
{
    //shorten string
    test = test.Substring(0,5)
}
Console.WriteLine(test);
Console.ReadLine();

With Substring you will get from character 0 to 4, adjust it to your need

Rodolfo
  • 247
  • 2
  • 14