Click here to Skip to main content
15,921,606 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Remove string from match word C#

for ex

string test="Remove string from match word.......";

if word is "from" then Remove string from " all string remove rest of all "
Posted
Updated 30-Jul-13 23:52pm
v3
Comments
Thomas Daniels 31-Jul-13 5:59am    
Incorrect, the OP wants to remove "from" and all after "from", not just "from".
[no name] 31-Jul-13 6:10am    
all right now ?

Try this
C#
string test="Remove string from match word.......";
int index1 = test.IndexOf("from");
if (index1 != -1)
{
    string result2 = test.Remove(index1);
}
else
{
  // "from" not found
}
 
Share this answer
 
v4
Comments
Thomas Daniels 31-Jul-13 5:57am    
I edited your answer: I removed the second parameter from test.Remove, because if you just write one parameter, then the written parameter is the startIndex parameter, and then all content from startIndex to the end of the string are removed. Also, always check whether the found index isn't -1.
Syed Shabeer 31-Jul-13 5:57am    
Thanks programFox...I realized only after posting it...
Thomas Daniels 31-Jul-13 5:58am    
You're welcome!
string test="Remove string from match word.......";

// first we get the index of from

int index = test.indexof("from");

test = test.substring(0,index)
 
Share this answer
 
v2
Comments
Thomas Daniels 31-Jul-13 5:59am    
Incorrect, the OP wants to remove "from" and all content after "from", not just "from".
[no name] 31-Jul-13 6:10am    
is it ok now ?
Thomas Daniels 31-Jul-13 6:45am    
Yes, it's ok now.
C#
string test = "Remove string from match word.......";
      int index = test.IndexOf("from");
      int l = test.Length;
      test = test.Substring(index+4);
 
Share this answer
 
Try this,
C#
string test="Remove string from match word.......";

if you want to remove only text "from" then,
C#
test = test.Replace("from","");

If you want to remove "from" and all text after "from" then,
C#
int index = test.IndexOf("from");
test = test.Substring(0,index);
 
Share this answer
 
v2
Comments
chetan2020 31-Jul-13 6:08am    
thanks
bt some chang needed becoz if index is -1 then getting error so

int index = test.IndexOf("from");
if(index != -1)
{
test = test.Substring(0,index);
}
Harshil_Raval 31-Jul-13 6:10am    
Thanks for make my answer more perfect.
hardiksedna 27-Feb-15 7:19am    
Really good optimized answer...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900