How to remove first two and last two chars in a string?

myString = myString.SubString(2, myString.Length - 4);

str = str.Substring(2,str.Length-4)

Of course you must test that the string contains more than 4 chars before doing this. Also in your case it seems that \n is a single newline character. If all you want to do is remove leading and trailing whitespaces, you should use

str.Trim()

as suggested by Charles


// Test string
var str = "\nTESTSTRING\n";

// Number of characters to remove on each end
var n = 2;

// Slimmed string
string slimmed;

if (str.Length > n * 2)
    slimmed = str.Substring(n, str.Length - (n * 2));
else
    slimmed = string.Empty;

// slimmed = "ESTSTRIN"

Did you try:

 myString.Trim();

Tags:

C#

String