Announcement

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

  • String manipulation - Keep all but the last 2 characters AND make first letter capital letter

    Hi,

    I would like to rename a string variable by deleting the last 2 characters (and keep all others) and also make the first letter a capital letter. Can someone help with that? I was trying with the command "substr" but could not get to the results. Thanks!


  • #2
    Francois, hope that the below code might help.

    Code:
    clear
    set obs 1
    gen varname = .
    local varnewname = strupper(substr("varname",1,1)) + substr("varname",2,length("varname")-3)
    ren varname `varnewname'
    Last edited by Romalpa Akzo; 27 Oct 2017, 08:03.

    Comment


    • #3
      substr() is a function, not a command. I guess that by "rename" you mean "replace". Strictly, I wouldn't replace any such variable without first being confident that I never needed the original again and second that my syntax was completely correct.

      After 363 posts here you should know

      (a) to show what you tried so that whatever misunderstandings are biting can be explained.

      (b) to give a data example.

      In other forums a post lacking in crucial details is just downvoted or people vote to close it as unclear!

      All that said, here is a toy example.

      Code:
      * Example generated by -dataex-. To install: ssc install dataex
      clear
      input str25 sandbox
      "frog"                    
      "toad"                    
      "dragon"                  
      "politician you don't like"
      end
      
      gen wanted = upper(substr(trim(sandbox), 1, 1)) + substr(trim(sandbox), 2, length(trim(sandbox)) - 3)
      
       list
      
           +-----------------------------------------------------+
           |                   sandbox                    wanted |
           |-----------------------------------------------------|
        1. |                      frog                        Fr |
        2. |                      toad                        To |
        3. |                    dragon                      Drag |
        4. | politician you don't like   Politician you don't li |
           +-----------------------------------------------------+
      trim() may be redundant for your case.

      EDIT: Romalpa in #2 nails the rename interpretation nicely. I didn't believe it, but there you go.
      Last edited by Nick Cox; 27 Oct 2017, 07:57.

      Comment


      • #4
        Not tested, but

        Code:
        rename varna?? ??
        rename <last two characters> , proper
        Best
        ​​​​​​​Daniel

        Comment

        Working...
        X