Announcement

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

  • Remove some characters from a string

    Dear Stata Users

    I have a string variable IssueCode. My aim is to end up with left 12 characters of this variable, for example 512KR7017170002 should become KR7017170002.

    I am aware of substr function but my problem is that not all variables have the same amount of characters, I have variables such as 30KR7005560008, 507KYG5307W1015. But all I need is to take 12 left characters...

    I have tried the following code but it does not work...

    gen IssueCode2=substr( IssueCode ,-1, - 12)


    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str16 IssueCode float(Price date)
    "7KR7200880003"    13450 20269
    "1058KR7006890008"  6150 20269
    "504KR7007570005"  77100 20269
    "30KR7005560008"       . 20269
    "507KYG5307W1015"      .     .
    end
    format %tdNN/DD/CCYY date

    What is the way around it?

    Thank you.
    Last edited by Olena Onishchenko; 04 Dec 2015, 01:15.

  • #2
    Following might work, if I am right in guessing that in all cases, you want to preserve the last 12 characters of the string.
    Use stringlength http://www.stata.com/manuals13/m-5st...-5strlen%28%29
    and substring http://www.stata.com/manuals13/m-5substr.pdf

    Code:
    gen codelength = strlen(IssueCode)
    gen codestartpos = codelength-11
    gen IssueCode2 = substr(IssueCode, codestartpos, 12)
    There may be cleaner ways, but this is simple and intuitive

    Comment


    • #3
      Thank you Jorrit for sush a prompt response and help.

      I just have tried the following, seems working...

      gen IssueCode2=substr( IssueCode ,-12,12)

      Hope it will serve my purpose for all cases.
      Last edited by Olena Onishchenko; 04 Dec 2015, 01:24.

      Comment


      • #4
        Another way around is to count 12 char from the end.
        Code:
         g a=substr(IssueCode,-12,.)

        Comment


        • #5
          Small tip. Once you know a function name you can go straight to its help by adding parentheses in a help call as in

          Code:
          help substr()
          which in this instance documents the possibility that a negative integer can be used to indicate a position counting from the end of a string or the values of a string variable.

          Comment


          • #6
            Right. Was unaware of that functionality of substr. That is neater.

            Comment

            Working...
            X