Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to enclose strings #10

Open
matthew-white opened this issue Mar 29, 2014 · 4 comments
Open

How to enclose strings #10

matthew-white opened this issue Mar 29, 2014 · 4 comments

Comments

@matthew-white
Copy link

Start with help quotes.

For each string in your program, determine whether it:

  1. Can be enclosed with simple double quotes (e.g., the string Hello world)
  2. Cannot be enclosed with simple double quotes, but can be enclosed with compound double quotes (e.g., "Hello world," he said.)
  3. Cannot be enclosed with simple or compound quotes (e.g., Unbalanced "compound" double quotes`)

To manage and manipulate strings in category (3), use extended macro functions or Mata.

If a string is in category (1) or (2), but you don't know which, usually you have to treat it like (3). Remember that some quotes can be enclosed with simple double quotes but cannot be enclosed with compound double quotes, e.g. the simple case of ```.

@matthew-white matthew-white added this to the Module on programs milestone Mar 29, 2014
@hdiamondpollock
Copy link
Contributor

Matt used to just replace all instances of ``` with ' so as to avoid the problem of having compound double quotes fail.

@matthew-white
Copy link
Author

For the non-programmer, the most common time this comes up is with levelsof and other programs that always use compound double quotes to enclose values; I've gotten related support requests a few times. For example:

clear
set obs 1
gen x = "`"
levelsof x

@matthew-white
Copy link
Author

Also related -- though probably not worth mentioning in this module -- is my Mata function specialexp(), which converts a string to an expression that evaluates to the string:

ssc install specialexp
help specialexp

The help file contains examples of difficult strings.

@matthew-white
Copy link
Author

One other point: replacing ``` with ' isn't guaranteed to work, because you still can't enclose unbalanced close compound double quotes with compound double quotes, i.e., `"'` has to be expressed as ``"""' + "'"`. If you're going to replace anything, perhaps better to replace double quotes. Then as long as you use the `macval()` expansion operator, I think you should be OK.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants