removinng last word from a string in c#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • madhurchadha
    New Member
    • Oct 2007
    • 1

    removinng last word from a string in c#

    how do i remove the last word from a string in c#


    suppose
    string is "hi how are you"
    i wanna remove you
  • Shashi Sadasivan
    Recognized Expert Top Contributor
    • Aug 2007
    • 1435

    #2
    use the indexOf to find the last index position of the space
    And then use substring.

    If you have issues with that, you could use a for loop, looping backwards from the string, and then use substring.

    If you still have issues with it, Please post what you have done until now and we will help you out

    Comment

    • aliasruel
      New Member
      • Sep 2007
      • 73

      #3
      Hi,

      string w="hi how are you";
      if (w.Length >0)
      {
      int p=w.LastIndexOf (" ") + 1;
      Response.Write( w.Substring(p)) ;
      }

      :)
      try that one now...
      regards!


      Originally posted by madhurchadha
      how do i remove the last word from a string in c#


      suppose
      string is "hi how are you"
      i wanna remove you

      Comment

      • Shashi Sadasivan
        Recognized Expert Top Contributor
        • Aug 2007
        • 1435

        #4
        Originally posted by aliasruel
        Hi,

        string w="hi how are you";
        if (w.Length >0)
        {
        int p=w.LastIndexOf (" ") + 1;
        Response.Write( w.Substring(p)) ;
        }

        :)
        try that one now...
        regards!
        A shorter one if You are interested:
        Code:
        s = "hi how are you";
        s.Substring(0, s.LastIndexOf(" ")<0?0:s.LastIndexOf(" "));
        Cheers.
        ------
        [CODE] Tags are great

        Comment

        Working...