Announcement

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

  • Removing space and special characters at the end of string characters

    I am trying to edit some string variables for use. I have a general query and a question more specific to the work that I am doing.

    General Query: If we want to remove a space at the end of a string variable, where there can be multiple spaces after the string elemets, how can this be done? For exmaple, supposing there is a string variable `x' and the elements of `x' are country names - Canada, Germany, Portugal etc. Now if there are spaces at the end of some observations and the number of spaces varies across observations, then would it be possible to use substr or subinstr to remove the spaces. Is there a way to distinguish between space and other string characters?

    Specific Query: I am working on a problem similar to what I stated above. In my case I have a string variable `stringvar' whose elements are names and some of the observations have an `*' at the end of the name. I tried the following set of codes:

    replace stringvar = subinstr(stringvar, "*", "", 1)

    and

    replace stringvar = subinstr(stringvar, "*", "", .)

    Both cases have yielded the same results, with these observations having extra spaces in place of the special character "*". And this is where my confusion arises. I was under the impression that " " denotes a space and "" denotes a null string. But in my case the above codes yield spaces when they are not supposed to.

    Could anybody please help with a solution?

  • #2
    Use trim() first.

    Comment


    • #3
      Arnab, on your General Query: use function strtrim()
      Code:
      replace country=strtrim(country)
      On your Specific Query, not sure what you mean. Your instruction tells Stata to replace a star (*) with nothing. This does not affect the trailing spaces.

      Best, Sergiy Radyakin

      Comment

      Working...
      X