Search in string

  • Thread starter Thread starter David
  • Start date Start date
D

David

Hello.

I have some basic question:)
How can I find last ", " symbol in string and replace it with " and "?

Thank you.
 
David said:
I have some basic question:)
How can I find last ", " symbol in string and replace it with " and "?

Use String.LastIndexOf to find the last ", " and then use
String.Substring twice to get the bits before and after:

int index = original.LastIndexOf(", ");
if (index==-1)
{
// Whatever you want to do if there isn't one
}
else
{
string newText = original.Substring (0, index)+
" and "+
original.Substring (index+2);
}
 
Hello.

I have some basic question:)
How can I find last ", " symbol in string and replace it with "
and "?

David,

You can use a regular expression that processes your string from
right-to-left, and tell it to only do one replacement:


using System;
using System.Text.RegularExpressions;

namespace Example
{
public class TestClass
{
public static int Main(string[] args)
{
Regex re = new Regex(", ", RegexOptions.RightToLeft);

Console.WriteLine(re.Replace("This, that, the other.", " and ", 1));

// prints "This, that and the other."

return 0;
}
}
}
 
Back
Top