Announcement

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

  • Easy way to obtain the position of a word in a string?

    Dear fellow Stata enthusiasts,

    I'm looking for a solution to the following rather simple problem:

    Saying I have a string

    Code:
    local foo = "Hello World!"
    and I now want to retrieve the position of the word "World!" in the string foo. I want to get the position of the word which in this case would be 2, because "World!" is the second word inside the string.

    (I know about the string functions (strpos(), etc.) but all of my solutions to this problem seem overcomplicated to me.)

    Thank You for your help!

    Max


  • #2
    I don't recall a dedicated function for this.

    Code:
    local foo "Hello World!" 
    
    local wnum = 0
    forval j = 1/`=wordcount("`foo'")' {
       if word("`foo'", `j') == "World!" local wnum = `j'
    }
    di `wnum'

    Comment


    • #3
      Thanks, Nick!

      I hoped there would have been a simpler solution, but I guess I'll have to make due with this.

      I just added a "continue, break", since I only want to get the position of the first occurence.

      Code:
      local foo "Hello World! Hello World!"
      local wnum = 0
      forval j = 1/`=wordcount("`foo'")' {
          if word("`foo'", `j') == "World!" {
              local wnum = `j'
              continue, break
          }
      }
      di `wnum'

      Comment


      • #4
        For anyone who may be searching the Statalist archives for how to obtain the position of a word in a string of multiple words, a shorter solution, perhaps more along the lines of what Max was looking for, is to use the macro function list in the following manner:
        Code:
        local foo "Hello World! Hello World!"
        local wnum: list posof "World!" in foo
        display `wnum'

        Comment

        Working...
        X