For example, I have a string containing "184553", how do I go about extracting the 3rd character "4" from string string and assigning it to another variable?

I have tried the following code but it does not work, the system crashes:

char string[6] = "184553";
printf("%s",string[2]); // Expecting it to print "4"

Any help??

hi there,

As you want to print a single character please use %c as the format specifier instead of %s. Also the size of string variable should be 7.
The code becomes as:

char string[7] = "184553";
   
      printf("%c",string[2]); //prints "4" now

Anirudh

Yes, %c should be used instead of %s. This isn't technically a C-string, just a simple array. A string would require 7 spaces, to accommodate for the NULL value at the end.

Yes, %c should be used instead of %s. This isn't technically a C-string, just a simple array. A string would require 7 spaces, to accommodate for the NULL value at the end.

No, technically it is a C-string. It has quotes which by definition ends in a NULL value. The definition actually overflows the array.

No, technically it is a C-string. It has quotes which by definition ends in a NULL value. The definition actually overflows the array.

Thank-you WaltP

I appreciate your technical prowess with these questions..and I hope you realize this is sincere...

Edited 5 Years Ago by gerard4143: n/a

When you want to declare an array of the same size as a const string literal then don't specify the array size so that the compiler can figure out the size itself char string[] = "184553";

This article has been dead for over six months. Start a new discussion instead.