2

I need to add quotes in begging and ending of a char.

char *Mychar = "hello"; 
printf("%c\n",Mychar[0]);

My result is h and my desired result is 'h'.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
user8978978
  • 101
  • 7
  • A `char` is specifically a single character, you can't have multiple characters inside one `char`, that's what `char[]` is for. If you just need to **print** `'h'`, then you can do `printf("'%c'\n",Mychar[0]);`, note the single quotes inside the double quotes. – hnefatl Dec 20 '17 at 20:07
  • 1
    Code **cannot** add `'` to a `char`. Code **can** add `'` to a _string_ or to a `printf()`. – chux - Reinstate Monica Dec 20 '17 at 20:23
  • 1
    Are you looking for something like`char *Mychar = "hello"; char quote_string[4] = {'\'', *Mychar, '\'', '\0'}; printf("%s\n",quote_string);` which prints `'h'\n`? – chux - Reinstate Monica Dec 20 '17 at 20:40

1 Answers1

3

Just add them in the format string. For single quotes, you can just put them in there:

printf("'%c'\n",Mychar[0]);

For double quotes, you'll have to escape them:

printf("\"%c\"\n",Mychar[0]);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Thank sir. Is it possible to add it before printf? char *Mychar = "hello"; char test='\n,Mychar[1],'\n;? – user8978978 Dec 20 '17 at 20:13
  • @user8978978: You could use `const char *Mychar = "'hello'";` or `const char *Mychar = "\"hello\"";`. (The `const` is semi-optional; you can't modify a string literal reliably -- it will crash your program on many systems -- so the `const` is appropriate to let the compiler know you know.) – Jonathan Leffler Dec 20 '17 at 20:17
  • I need to get 'h' – user8978978 Dec 20 '17 at 20:20
  • @user8978978 `%c` can only format a single character. `'h'` is 3 characters, it needs to be a string. – Barmar Dec 20 '17 at 20:28
  • i need to separate each char of a string with single quote in front and in end.Examle string hello i need to take 'h' , 'e', 'l', 'l' ,'o' in a string – user8978978 Dec 20 '17 at 20:40