How to remove first two and last two chars in a st

2020-07-06 07:59发布

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?

标签: c# string
8条回答
太酷不给撩
2楼-- · 2020-07-06 08:35
// 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"
查看更多
可以哭但决不认输i
3楼-- · 2020-07-06 08:36

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

查看更多
Ridiculous、
4楼-- · 2020-07-06 08:36
    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;
    }
查看更多
Evening l夕情丶
5楼-- · 2020-07-06 08:38

Did you try:

 myString.Trim();
查看更多
小情绪 Triste *
6楼-- · 2020-07-06 08:45
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

查看更多
干净又极端
7楼-- · 2020-07-06 08:51

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
查看更多
登录 后发表回答