12

I would like a to define a variable string in C that contains the following set of characters: a-zA-Z0-9'-_”.

Therefore I would do it like this:

char str[64] = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789'-_""

As you can see the problem is at the end with " character.

Question 1: How can I work around that?

Question 2: Is there a better way than my way to define a string like that?

PS: I didn't really know how to title my question, so if you got a better one, please edit it.

Dragos Rizescu
  • 3,380
  • 5
  • 31
  • 42
  • 1
    Escape the last quotation mark: `\"` – godel9 Dec 08 '13 at 20:15
  • 1
    Escape it with the backslash: `"\""`. Note that with `str[64]` you have enough space for all your 64 characters, but not for a null-terminator. Depending on how you plan to use the string this might be a problem. With this initialisation though, specifying the length is optional so `char str[] = "...";` is valid and will automatically make the buffer big enough to contain the string + null-terminator. – Kninnug Dec 08 '13 at 20:15
  • Unless you've omitted some letters that I didn't notice that's 66 characters. – Hot Licks Dec 08 '13 at 20:22
  • @HotLicks I copied & pasted it into Notepad++ which counted 64 characters: there are no v's in it (upper- nor lower-case). – Kninnug Dec 08 '13 at 20:24
  • 3
    Churchill would be disappointed. – Hot Licks Dec 08 '13 at 20:28
  • Second question: it depends. What are you using this string for? Can the same thing be done using code? Can the same thing be done using its inverse -- a list of printable ASCII characters that are *not* in this list (about 30, with or without "v")? Can you use a bitmap array instead of literal characters? Can you use `ctype` instead? – Jongware Dec 08 '13 at 21:09

2 Answers2

17

use the backslash: "\"" is a string containing "

like this:

char str[67] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'-_\"";

added one for the implicit '\0' at the end (and put in the missing vV) - this could also be:

char str[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'-_\"";

and let the compiler count for you - then you can get the count with sizeof(str);

How does it add up to 67?

a-z 26
A-Z 26
0-9 10
'-_" 4
'\0' 1
    ---
    67
Glenn Teitelbaum
  • 10,108
  • 3
  • 36
  • 80
6

Use "\"" (backslash") for putting " in a string

Bilal Syed Hussain
  • 8,664
  • 11
  • 38
  • 44