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??

Recommended Answers

All 7 Replies

Like so

char my_ch = string[2];

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.

My mistake

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...

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";

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.