views:

164

answers:

6

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? :

  1. Know the position in which "something" is located (in the curr. ex. this is = 0.
  2. Extract everything to the left or to the right, up to the char. found (see 1).
  3. Extract a substring beggining where the sought string was found, all the way to X amount of chars (in Visual Basic 6/VBA I would use the Mid function).
+1  A: 

Have you looked at the String.SubString() method? You can use the IndexOf() method to see if the substring exists first.

Ed Swangren
Don't forget .Contains()
Joel Coehoorn
Yes, that works too, but the OP was looking for a way to extract the substring. Contains() would only tell him whether it could be found. IndexOf would be more useful in this case
Ed Swangren
A: 

Take a look at the System.String member functions, in particular the IndexOf method.

dirkgently
+9  A: 
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);
Moose
@bdukes: thanks for the edit, I was still missing the quotes around "something" afterwards.
Moose
Number 2 wont work since you are not taking into account the lenght of "something". Using the split method is easier.
Igor Zelaya
@Igor: Depends on your interpretation of #2. "up to the char. found (see 1)." to me, means what was returned by IndexOf. For your interpretation, your method is valid.
Moose
Works great. How can I code this into a class, that becomes publicly available to any Visual Studio project?
A: 

Use int String.IndexOf(String).

Samuel
A: 

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);
Igor Zelaya
A: 

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

Adam Robinson