Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. how can i get the last word from the string

how can i get the last word from the string

Scheduled Pinned Locked Moved C#
questiontutorial
13 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A ahmedhassan96

    hi every body i want know hot can i get the last word from string which inputed from user example: user entered:"my favorite song is ttt.mp3"; my question is how can i get "ttt.mp3" from the string thanx every one

    M Offline
    M Offline
    Mycroft Holmes
    wrote on last edited by
    #4

    split the string into an array using a space as the delimiter and get the last element in the array or identify the last space in the string and get the trailing characters

    Never underestimate the power of human stupidity RAH

    1 Reply Last reply
    0
    • A ahmedhassan96

      hi every body i want know hot can i get the last word from string which inputed from user example: user entered:"my favorite song is ttt.mp3"; my question is how can i get "ttt.mp3" from the string thanx every one

      E Offline
      E Offline
      Eslam Afifi
      wrote on last edited by
      #5

      System.Text.RegularExpressions.Regex.Match(input, @"\S*$");

      Edit: a better solution here[^].

      Eslam Afifi

      modified on Sunday, September 14, 2008 11:21 AM

      1 Reply Last reply
      0
      • A ahmedhassan96

        hi every body i want know hot can i get the last word from string which inputed from user example: user entered:"my favorite song is ttt.mp3"; my question is how can i get "ttt.mp3" from the string thanx every one

        M Offline
        M Offline
        Mohammad Dayyan
        wrote on last edited by
        #6

        Try this :

        static void Main()
        {
        string temp = "my favorite song is ttt.mp3";
        Console.WriteLine("Last word = {0}", Regex.Match(temp.Trim(), @"[^\s]*$" ).ToString() ) ;
        Console.ReadKey();
        }

        M realJSOPR 2 Replies Last reply
        0
        • M Mohammad Dayyan

          Try this :

          static void Main()
          {
          string temp = "my favorite song is ttt.mp3";
          Console.WriteLine("Last word = {0}", Regex.Match(temp.Trim(), @"[^\s]*$" ).ToString() ) ;
          Console.ReadKey();
          }

          M Offline
          M Offline
          Mycroft Holmes
          wrote on last edited by
          #7

          I hate people who know regex - what an arcane, completely undecipherable load of... Take 5

          Never underestimate the power of human stupidity RAH

          1 Reply Last reply
          0
          • M Mohammad Dayyan

            Try this :

            static void Main()
            {
            string temp = "my favorite song is ttt.mp3";
            Console.WriteLine("Last word = {0}", Regex.Match(temp.Trim(), @"[^\s]*$" ).ToString() ) ;
            Console.ReadKey();
            }

            realJSOPR Offline
            realJSOPR Offline
            realJSOP
            wrote on last edited by
            #8

            Why burden the app with regex? Someone else gave what is, in my humble aopinion, a much better solution using LastIndexOf(" ").

            "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
            -----
            "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

            M E 2 Replies Last reply
            0
            • realJSOPR realJSOP

              Why burden the app with regex? Someone else gave what is, in my humble aopinion, a much better solution using LastIndexOf(" ").

              "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
              -----
              "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

              M Offline
              M Offline
              Mohammad Dayyan
              wrote on last edited by
              #9

              You're right. Thank you John.

              1 Reply Last reply
              0
              • realJSOPR realJSOP

                Why burden the app with regex? Someone else gave what is, in my humble aopinion, a much better solution using LastIndexOf(" ").

                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                -----
                "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                E Offline
                E Offline
                Eslam Afifi
                wrote on last edited by
                #10

                In my humble opinion, the LastIndexOf(" ") solution will fail in case of other white space characters or if the string contains one word only. In fact an expression like @"\S*(?=\s*$)" would be better as it matches the last non-whitespace character combination in the string.

                Eslam Afifi

                realJSOPR 1 Reply Last reply
                0
                • E Eslam Afifi

                  In my humble opinion, the LastIndexOf(" ") solution will fail in case of other white space characters or if the string contains one word only. In fact an expression like @"\S*(?=\s*$)" would be better as it matches the last non-whitespace character combination in the string.

                  Eslam Afifi

                  realJSOPR Offline
                  realJSOPR Offline
                  realJSOP
                  wrote on last edited by
                  #11

                  The OP's example CLEARLY indicatedc spaces were being used to separate words in a TextBox. What other kind of whitespace characters did you have in mind? First, using RegEx obfuscates the intent of the code, and slows it down besides. I can count on ONE HAND the number of people I know that would use RegEx over the much simpler construct of LastIndexOf(). As soon as new programmers learn that readability and maintainability is much more important than "clever code", we'll all be a lot better off. Sure, RegEx has it's place, but not for this problem. A valid example of requiring RegEx is validating that an email address is properly formatted. But for finding the last word in a string of words separated by spaces? Not on your life.

                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                  -----
                  "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                  E 1 Reply Last reply
                  0
                  • realJSOPR realJSOP

                    The OP's example CLEARLY indicatedc spaces were being used to separate words in a TextBox. What other kind of whitespace characters did you have in mind? First, using RegEx obfuscates the intent of the code, and slows it down besides. I can count on ONE HAND the number of people I know that would use RegEx over the much simpler construct of LastIndexOf(). As soon as new programmers learn that readability and maintainability is much more important than "clever code", we'll all be a lot better off. Sure, RegEx has it's place, but not for this problem. A valid example of requiring RegEx is validating that an email address is properly formatted. But for finding the last word in a string of words separated by spaces? Not on your life.

                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                    -----
                    "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                    E Offline
                    E Offline
                    Eslam Afifi
                    wrote on last edited by
                    #12

                    John Simmons / outlaw programmer wrote:

                    The OP's example CLEARLY indicatedc spaces were being used to separate words in a TextBox.

                    but the question stated

                    ahmedhassan96 wrote:

                    hot can i get the last word from string which inputed from user

                    and he didn't explicitly mention the delimiter used. Your post made me think of other white space characters such as Tab and NewLine (depends on how he gets the input string from the user). I'm aware that readability and maintainability is more important than clever code, and i wasn't trying to be clever. I just think a simple regex is much less in code than using LastIndexOfAny and handling the -1 return case.

                    Eslam Afifi

                    1 Reply Last reply
                    0
                    • A ahmedhassan96

                      hi every body i want know hot can i get the last word from string which inputed from user example: user entered:"my favorite song is ttt.mp3"; my question is how can i get "ttt.mp3" from the string thanx every one

                      S Offline
                      S Offline
                      Shweta Gulati
                      wrote on last edited by
                      #13

                      It will be much more easy and simple to use 'lastindexof' So you can use this: string lastword; int lastindex = str.LastIndexOf(" ")-1; int len = str.Length; if (lastindex == -1) //if there is only one word in the string { lastword = str; } else { lastword = str.Substring(lastindex, (len - lastindex)); } //here str is the string from which last word has to be taken

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups