ahpitre
ahpitre

Reputation:

String functions

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

Upvotes: 0

Views: 1209

Answers (6)

Adam Robinson
Adam Robinson

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

Igor Zelaya
Igor Zelaya

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

Moose
Moose

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

Samuel
Samuel

Reputation: 38346

Use int String.IndexOf(String).

Upvotes: 0

dirkgently
dirkgently

Reputation: 111120

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

Upvotes: 0

Ed Swangren
Ed Swangren

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

Related Questions