views:

106

answers:

4

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 length is not fixed)
  • But the word will contain the "/NN" part at the end always.

How can I do this in C# .NET?

+1  A: 

Simply use

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

edit

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

Øyvind Bråthen
Agreed - and just to clarify if you're a beginner, you need to set word = word.Replace(@"/NN","");
Vixen
Harsh to call me a beginner because I forgot to add word =, but thats your choice...
Øyvind Bråthen
actually this won't work so great if there is a chance that "/NN" will appear more than one time inside text, i.e. consider string "c/NNeee/NN"
tchrikch
I used Replaced and it worked.Thanks :)
sunshine
+3  A: 

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('/'));
dtb
Thanks a lot :)
sunshine
A: 

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);
Vinay B R
I did try this but it gave me an error saying that I am missing an assembly reference for Regex.
sunshine
+3  A: 

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.

VVS
Thanks :).This works well for me.
sunshine