Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a string like

C#
string str=" Motin AS fahami.menu.Asgar AS ASRAF"


I always want to get the string befire last occurring AS. This AS is always consider as single AS. This 'AS' will not consider the portion ASRAF where first two word also indicate AS.

The out will be same as 'Motin AS fahami.menu.Asgar'.

if the code is like that

C#
string str=" Motin AS fahami.menu.ASIM AS SUVASISH"


then the out put will : Motin AS fahami.menu.ASIM

can anyone provide me the code for that?
Posted

See this:
C#
string str=" Motin AS fahami.menu.ASIM AS SUVASISH";
string str2;
int i = str.LastIndexOf(" AS ");
str2 = str.Substring(0, i);
 
Share this answer
 
A fairly clunky way would be:

C#
string delimiter = " AS ";  //note the spaces either side
string str = "Motin AS fahami.menu.ASIM AS anything that doesn't contain the delimiter";
string[] elements = System.Text.RegularExpressions.Regex.Split(str, delimiter);
string result = elements[0] + delimiter + elements[1];
 
Share this answer
 
Hi, if i did understood right your need,
Then here is what you need:

C#
string str=" Motin AS fahami.menu.ASIM AS SUVASISH"

if(str.Contains(" AS ")) //if you use indexOf in a string without being sure the string conatins your search string, an exception will be thrown
{               
                //gett the index of the last occurance
                int idexOfLastOccurance = str.LastIndexOf(" AS ");
                //Remove all the text starting from the index      
                str = str.Remove(idexOfLastOccurance);
}
 
Share this answer
 
Hi,

use str.substring(str.LastIndexOf('AS')+1)

Regards,
Bh@gyesh
 
Share this answer
 
Comments
Sprint89 22-May-14 6:24am    
I tried that on "Motin AS fahami.menu.ASIM AS SUVASISH" and got "SISH"
string str=" Motin AS fahami.menu.Asgar AS ASRAF"
var lst=str.Split(" ",str).ToList();
lst.RemoveAt(lst.Count()-1);
lst.RemoveAt(lst.Count()-2);

string substring=string.Join(" ",lst)
 
Share this answer
 
Comments
CHill60 22-May-14 9:07am    
This doesn't even compile! Nor would it work if it did.

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