Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all

I have a text like this for example:

there is a new care here, nothing else

how can I get a sub string from it

for example I want the string from word new to word nothing to get

new care here, nothing


thank you all : )
Posted
Comments
VJ Reddy 6-Jun-12 1:59am    
Thank you for accepting the solution :)

If you know for sure the the start word you are looking for is "new" and the end word is "nothing" you can search for these words in your string and find their index. Once you have the index, you can use that to do the substring.

Here[^] is an MSDN article that can explain it with a good example.

The problem you may encounter, is if there is more than one word "new" or "nothing" in your sentence.

Hope this helps.
 
Share this answer
 
Comments
VJ Reddy 5-Jun-12 13:01pm    
Good answer. 5!
Sergey Alexandrovich Kryukov 5-Jun-12 13:26pm    
Looking for "new" and "nothing"... -- nothing new :-) My 5 though. :-)
--SA
Maciej Los 5-Jun-12 14:45pm    
;)
thatraja 5-Jun-12 15:26pm    
5!
The Regex class can be used to retrieve the required sub string from the above text.

If only first occurrence of the sub string is required then the Match method of Regex can be used as follows:
C#
string text = @"there is a new care here, nothing else";
Match match = Regex.Match(text,@"new.*?nothing",
    RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
if (match.Success)
	Console.WriteLine (match.Value);
//Output
//new care here, nothing

If multiple occurrences of the sub string is required then the Matches method of Regex class can be used as follows:

C#
string text2 = @"there is a new care here, nothing second new care here second time, nothing else";
MatchCollection matches = Regex.Matches(text2,@"new.*?nothing",
    RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
foreach (Match m in matches)
{
    Console.WriteLine (m.Value);
}
//Output
//new care here, nothing
//new care here second time, nothing
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 5-Jun-12 13:24pm    
Sure, a 5.
--SA
VJ Reddy 5-Jun-12 13:26pm    
Thank you, SA :)
Maciej Los 5-Jun-12 14:46pm    
Good answer, my 5!
VJ Reddy 5-Jun-12 19:37pm    
Thank you, losmac :)
thatraja 5-Jun-12 15:26pm    
Regex is better option, 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900