views:

497

answers:

5

Is there an easy way to remove the first 2 and last 2 chars in a string?

I have this string:

\nTESTSTRING\n

How could I easily delete them?

+4  A: 

Did you try:

 myString.Trim();
Chuck Conway
\n is ONE char.
Matajon
+2  A: 
myString = myString.SubString(2, myString.Length - 4);
Ciwee
Needs a check for `Length < 4`.
Pavel Minaev
(myString == ESTSTRIN ) == true
Muad'Dib
+9  A: 
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

Manu
This is the correct answer to the question as asked, but it sounds like the OP doesn't realize that \n is the escape for a newline.
JSBangs
The first part is correct for my use. The second one isn't applicable because I'm using it on HTML, and using the .Trim() doesn't remove the whitespace at all.
Sergio Tapia
+3  A: 
// 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"
cdmckay
A: 

Papuccino1,

If you create an extension method like this:

 public static class StringEnumerator {

    public static IEnumerable<String> GetLines(this String source) {
        String line = String.Empty;
        StringReader stringReader = new StringReader(source);

        while ((line = stringReader.ReadLine()) != null) {
            if (!String.IsNullOrEmpty(line)) {
                yield return line;
            }
        }
    }
}

your code will be simplified and will be safer (not depending on dangerous index):

class Program {

    static void Main(string[] args) {
        String someText = "\nTESTSTRING\n";
        String firstLine = someText.GetLines().First();
    }
}

I hope this helps,

Ricardo Lacerda Castelo Branco

Ricardo Lacerda Castelo Branco