开发者

How to delete certain characters of a word in c#

I have a

string word = "degree/NN";

What I want is to remove the "/NN" part of the word and take only the word "degree".

I have following conditions:

  • The length of the word can be different in different occasions. (can be any word therefore the 开发者_C百科length is not fixed)
  • But the word will contain the "/NN" part at the end always.

How can I do this in C# .NET?


Implemented as an extension method:

static class StringExtension
{
  public static string RemoveTrailingText(this string text, string textToRemove)
  {
    if (!text.EndsWith(textToRemove))
      return text;

    return text.Substring(0, text.Length - textToRemove.Length);
  }
}

Usage:

string whatever = "degree/NN".RemoveTrailingText("/NN");

This takes into account that the unwanted part "/NN" is only removed from the end of the word, as you specified. A simple Replace would remove every occurrence of "/NN". However, that might not be a problem in your special case.


You can shorten the input string by three characters using String.Remove like this:

string word = "degree/NN";

string result = word.Remove(word.Length - 3);

If the part after the slash has variable length, you can use String.LastIndexOf to find the slash:

string word = "degree/NN";

string result = word.Remove(word.LastIndexOf('/'));


Simply use

word = word.Replace(@"/NN","");

edit

Forgot to add word =. Fixed that in my example.


Try this -

  string.replace();

if you need to replace patterns use regex replace

  Regex rgx = new Regex("/NN");
  string result = rgx.Replace("degree/NN", string.Empty);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜