如何删除字符串中的前两个和后两个字符?

时间:2009-10-20 22:03:23

标签: c# string

是否有一种简单的方法可以删除字符串中的前2个字符和后2个字符?

我有这个字符串:

\nTESTSTRING\n

我怎么能轻易删除它们?

8 个答案:

答案 0 :(得分:47)

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

当然,在执行此操作之前,您必须测试该字符串是否包含4个以上的字符。在你的情况下,似乎\ n是一个换行符。如果您只想删除前导和尾随空格,则应使用

str.Trim()

根据查尔斯的建议

答案 1 :(得分:6)

// 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"

答案 2 :(得分:5)

你有没有尝试过:

 myString.Trim();

答案 3 :(得分:2)

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

答案 4 :(得分:0)

Papuccino1,

如果您创建这样的扩展方法:

 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;
            }
        }
    }
}

您的代码将被简化并且更安全(不依赖于危险索引):

class Program {

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

我希望这有帮助,

Ricardo Lacerda Castelo Branco

答案 5 :(得分:0)

    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;
    }

答案 6 :(得分:0)

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

答案 7 :(得分:0)

使用SubstringRemove方法简单,详见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