Reputation: 779
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:
"/NN"
part at the end always.How can I do this in C# .NET?
Upvotes: 1
Views: 3553
Reputation: 19612
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.
Upvotes: 4
Reputation: 217401
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('/'));
Upvotes: 4
Reputation: 60734
Simply use
word = word.Replace(@"/NN","");
edit
Forgot to add word =. Fixed that in my example.
Upvotes: 2
Reputation: 8421
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);
Upvotes: 0