Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Extracting letters from a string

    Hello!

    I want to generate a new string variable from an old string variable that consists of everything except the last letter.

    Consider the following example where I want to generate a new variable where the word is in singular instead of plural.


    string1 | string2

    balls | ball
    tables | table
    rings | ring


    How do I go from string1 to string2?

    I have tried substr(), but it haven't been able to make it work since it doesn't count backwards, or does it?


    Shikasta

  • #2
    Code:
    gen string2 = substr(string1, 1, length(string1) - 1)
    substr() certainly can count backwards, but in this case I don't see that would help you much. You still want to start at the beginning and the second argument of substr() is a length, not a position.

    Code:
    . di substr("Stata shines", -6, 6)
    shines

    Too devious by half is

    Code:
     
    reverse(substr(reverse(string1), 2, .)))


    Last edited by Nick Cox; 04 Mar 2015, 12:46.

    Comment


    • #3
      Thank you Nick!

      The answer was simple! Using the length of the word instead of a position.

      Comment

      Working...
      X