Reputation:
I want to search for a given string, within another string (Ex. find if "something" exists inside "something like this". How can I do the following? :
Upvotes: 0
Views: 1209
Reputation: 185593
I would avoid using Split, as it's designed to give you multiple results. I would stick with the code in the first example, though the second block should actually read...
string start = searched.Substring(0, pos);
string endstring;
if(pos < searched.Length - 1)
endstring = searched.Substring(pos + "something".Length);
else
endstring = string.Empty
The key difference is accounting for the length of the string to find (hence the rather odd-looking "something".Length, as this example is designed for you to be able to plop in your own variable).
Upvotes: 0
Reputation: 4277
I would do something like this:
string s = "I have something like this";
//question No. 1
int pos = s.IndexOf("something");
//quiestion No. 2
string[] separator = {"something"};
string[] leftAndRightEntries = s.Split(separator, StringSplitOptions.None);
//question No. 3
int x = pos + 10;
string substring = s.Substring(pos, x);
Upvotes: 0
Reputation: 5412
string searched = "something like this";
1.
int pos = searched.IndexOf("something");
2.
string start = searched.Substring(0, pos);
string endstring = searched.Substring(pos);
3.
string mid = searched.Substring(pos, x);
Upvotes: 10
Reputation: 111120
Take a look at the System.String member functions, in particular the IndexOf method.
Upvotes: 0
Reputation: 124632
Have you looked at the String.SubString() method? You can use the IndexOf() method to see if the substring exists first.
Upvotes: 1