开发者

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

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

I have this 开发者_如何学Cstring:

\nTESTSTRING\n

How could I easily delete them?


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();


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


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


string Origional = TextBox1.Text.Replace(TextBox1.Text.Substring(0, 2), "");
Origional += Origional.Replace(Origional.Substring((Origional.Length - 2), 2), "");


    public string RemoveFirstCharFromString(string Text)
    {
        string[] arr1 = new string[] { "The ", "A " };

        string Original = Text.ToLower();
        if (Text.Length > 4)
        {
            foreach (string match in arr1)
            {
                if (Original.StartsWith(match.ToLower()))
                {
                    //Original = Original.Replace(match.ToLower(), "").TrimStart();
                    Original = Original.Replace(Original.Substring(0, match.Length), "").TrimStart();
                    return Original;
                }
            }
        }
        return Original;
    }


Its Simple with Substring and Remove methods, as detailed in this link:

string mystring = "122014";

mystring = mystring.Substring(mystring.Length - 4);
Response.Write(mystring.ToString());

//output:2014


mystring = "122014";
string sub = mystring.Remove(mystring.Length - 4);
Response.Write("<br>");
Response.Write(sub.ToString());

//output: 12
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜