In my opinion, I want to remove only '01|CF' out string '01|CFV,01|CFY,01|CF' to '01|CFV,01|CFY'. But have 3 mark '01|CF' in this string, so if replace string, i will take to result 'V,Y,'. I want to know how to solve that
string stringToSearch = "01|CF";
string stringToBeSearched = "01|CFV,01|CFY,01|CF";
CodePudding user response:
First 01|CF replace with "" and remain V, Second 01|CF replace with "" and remain Y, And third 01|CF replace with "" and remain nothing Result: V,Y,
CodePudding user response:
In your comments you elaborate further into your problem and notice why it does display that output:
I want to remove only
01|CF
' out string01|CFV,01|CFY,01|CF
to01|CFV,01|CFY
. But have 301|CF
matches in this string, so if I usestring.Replace()
, I will take to resultV,Y,
. I want to know how to solve that.
The trick is using a different approach. You need to locate the last match of the 01|CF
using string.LastIndexOf() and based on that index/position get the part of the string that you want using string.Substring().
string stringToSearch = "01|CF";
string stringToBeSearched = "01|CFV,01|CFY,01|CF";
int lastMatchPosition = stringToBeSearched.LastIndexOf(stringToSearch);
string firstPart = stringToBeSearched.Substring(0, lastMatchPosition - 1);
Console.WriteLine(firstPart);
It outputs:
01|CFV,01|CFY