views:

89

answers:

5

I have a string of source code HTML.

So I would go:

int X = find indexof("theterm");
thesourcecode = thesourcecode.Substring(????

How can I delete all chars from the point where theterm is found BEHIND? Thanks SO.

Edit: An example so people dont' get confused.

Sample string: "The big red house is so enormous!"

int Position = sampleString.IndexOf("house");

(pseudocode) From point Position, and back, delete everything:

Result string after my method: "is so enourmous!

+2  A: 
// this could be set explicitly or variable based on user input.  
   string mySearchString = "TextToFind";

THe code below assumes that this will change, otherwise I would have used the number 10 instead of mySearchString.Length.

int foundIndex = myString.IndexOf(mySearchString);

Once you've found the index it's easy:

Remove all the text before your string

myString = myString.SubString(0, foundIndex);

or remove all the text after your search text.

myString = myString.SubString(foundIndex + mySearchString.Length, myString.Length - 1);
David Stratton
xD I can't believe it was that simple. Thanks bro.
Sergio Tapia
You don't need the second parameter in substring in your second example. The default when using one parameter is till the end of the string.
BFree
Your example seems a little confusing. Shouldn't "remove" be replaced by "getting"? Or "before" and "after" be swapped and the indeces be adjusted?
0xA3
@BFree - thanks. That makes sense. I think I put it in there out of habit.
David Stratton
+1  A: 

If you mean removing all characters preceding a character, you would do:

string s = "i am theterm";
int index = s.IndexOf("theterm");
s = s.Substring(index, s.Length - index);
nasufara
A: 

You would simply write

thesourcecode = thesourcecode.Substring(X);

For instance if we did the following:

string s = "Hello there everybody!";
s = s.Substring(s.IndexOf("the"));

s would now equal "there everybody!"

Vincent McNabb
A: 
thesourcecode = thesourcecode.Remove(0, thesourcecode.IndexOf("theterm"));
TruthStands
You would have to add the length of the searched text as well.
0xA3
A: 

Untested:

var index = thesourcecode.IndexOf("theterm");
thesourcecode = thesourcecode.Substring(index);
gWiz