Click here to Skip to main content
15,902,492 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi I have a string like this
"[fconsender]Username (11:00 AM):[/fconsender] Hi Good Afternoon!"

or
"[fconreceiver]AnotherUser (11:02 AM):[/fconreceiver] Yea! How are you ?"


I want to extract the string inside [fconsender] and [/fconsender] or
[fconreceiver] and [/fconreceiver]...
How can I simply achieve it without using much loops,,.
Its just to change the colour of sender/reciever name...
Posted
Updated 27-Nov-13 21:25pm
v3

You can use following function..

C#
string GetMiddleString(string input, string firsttoken, string lasttoken)
{
    int pos1 = input.IndexOf(firsttoken) + 1;
    int pos2 = input.IndexOf(lasttoken);
    string result = input.Substring(pos1 , pos2 - pos1);
    return result
}



http://stackoverflow.com/a/2449659[^]
 
Share this answer
 
Comments
Karthik_Mahalingam 28-Nov-13 4:07am    
check once please...
Try this code..

works fine..



C#
string input = "[fconsender]Username (11:00 AM):[/fconsender] Hi Good Afternoon!";
           string starttag = "[fconsender]";
           string endtag = "[/fconsender]";
           int sindex = input.IndexOf(starttag) + starttag.Length;
           int length = input.IndexOf(endtag) - starttag.Length;
           string output = input.Substring(sindex, length);
 
Share this answer
 
Just for the sake of variety:
C#
private string s1 = "[fconsender]Username (11:00 AM):[/fconsender] Hi Good Afternoon!";

private string s2 = "[fconreceiver]AnotherUser (11:02 AM):[/fconreceiver] Yea! How are you ?";

private string getInnerText(string theText)
{
    return (theText.Contains("sender"))
        ? theText.Substring(12, theText.IndexOf('[', 1) - 12)
        : theText.Substring(14, theText.IndexOf('[', 1) - 14);
}

private void Test_getInnerText()
{
    string s3 = getInnerText(s1);
    string s4 = getInnerText(s2);

    Console.WriteLine("{0},\r\n{1}", s3, s4);
}
Yes, I know the dangers of using "hard-coded" indexes; if you don't, forget this code :)
 
Share this answer
 

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