locked
Replace last occurance of , with the word "and" RRS feed

  • Question

  • User756585424 posted

    All, How do you replace the last occurance of a , with the word and? Can you please give me an example using this string

     

    "My favorite books are book1, book2, book3, book4."

    I would like the output to be like this:  "My favorite books are book1, book2, book3 and book4."

     

    I have the code to remove a which i got from this forum, but not sure how to replace it:

    Dim strChar As String = "AAA,BBB,CCC,"
    If strChar.Contains(",") Then
        If strChar.LastIndexOf(",") = strChar.Length - 1 Then
            strChar = strChar.Substring(0, strChar.LastIndexOf(","))
        End If
        Response.Write(strChar)  ' THIS WOULD OUTPUT AAA,BBB,CCC
    End If 

    Monday, June 16, 2008 2:48 PM

Answers

  • User-520527587 posted

    Give this a shot.

      

    string myString = "I like foo, bar, foobar, barfoo";
    int commaIndex = myString.LastIndexOf(",");
    mystring = mystring.Substring(0, commaIndex) + " and" + mystring.Substring(commaIndex + 1);
     

    I hope that helps,
    Brendan 

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 16, 2008 3:00 PM

All replies

  • User653228039 posted

    Honestly, I'd just concatenate " And " to the string you created with your substring.

    Monday, June 16, 2008 2:58 PM
  • User-520527587 posted

    Give this a shot.

      

    string myString = "I like foo, bar, foobar, barfoo";
    int commaIndex = myString.LastIndexOf(",");
    mystring = mystring.Substring(0, commaIndex) + " and" + mystring.Substring(commaIndex + 1);
     

    I hope that helps,
    Brendan 

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 16, 2008 3:00 PM
  • User756585424 posted

     Nice.  It works.  Thank you.  You guys just saved me a good amount of time that I would've spend trying to figure this out.  I love this forum.  

     

    MikeB55 

    Monday, June 16, 2008 3:03 PM