Sergio Tapia
Sergio Tapia

Reputation: 41128

How can I delete chars from a string from point X to the beginning

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!

Upvotes: 0

Views: 1218

Answers (5)

G-Wiz
G-Wiz

Reputation: 7426

Untested:

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

Upvotes: 0

TruthStands
TruthStands

Reputation: 93

thesourcecode = thesourcecode.Remove(0, thesourcecode.IndexOf("theterm"));

Upvotes: 0

Vincent McNabb
Vincent McNabb

Reputation: 34659

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!"

Upvotes: 0

user153498
user153498

Reputation:

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);

Upvotes: 1

David
David

Reputation: 73564

// 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);

Upvotes: 2

Related Questions