-2

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
  • 23
  • 1
  • 3
  • 6

3 Answers3

8

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,483
  • 6
  • 47
  • 84
2

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
  • 26,733
  • 2
  • 34
  • 59
0

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
  • 237
  • 2
  • 14