开发者

Is there an easy way to trim the last three characters off a string

I have strings like 开发者_JS百科this:

var a = "abcdefg";
var b = "xxxxxxxx";

The strings are always longer than five characters.

Now I need to trim off the last 3 characters. Is there some simple way that I can do this with C#?


In the trivial case you can just use

result = s.Substring(0, s.Length-3);

to remove the last three characters from the string.

Or as Jason suggested Remove is an alternative:

result = s.Remove(s.Length-3)

Unfortunately for unicode strings there can be a few problems:

  • A unicode codepoint can consist of multiple chars since the encoding of string is UTF-16 (See Surrogate pairs). This happens only for characters outside the basic plane, i.e. which have a code-point >2^16. This is relevant if you want to support Chinese.
  • A glyph (graphical symbol) can consist of multiple codepoints. For example ä can be written as a followed by a combining ¨.
  • Behavior with right-to-left writing might not be what you want either


You want String.Remove(Int32)

Deletes all the characters from this string beginning at a specified position and continuing through the last position.

If you want to perform validation, along the lines of druttka's answer, I would suggest creating an extension method

public static class MyStringExtensions
{
  public static string SafeRemove(this string s, int numCharactersToRemove)
  {
    if (numCharactersToRemove > s.Length)
    {
      throw new ArgumentException("numCharactersToRemove");
    }

    // other validation here

    return s.Remove(s.Length - numCharactersToRemove);
  }
}

var s = "123456";
var r = s.SafeRemove(3); //r = "123"
var t = s.SafeRemove(7); //throws ArgumentException


string a = "abcdefg";
a = a.Remove(a.Length - 3);


string newString = oldString.Substring(0, oldString.Length - 4);


If you really only need to trim off the last 3 characters, you can do this

string a = "abcdefg";
if (a.Length > 3)
{
  a = a.Substring(0, a.Length-3);
}
else
{
  a = String.Empty;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜