views:

70

answers:

1

In javascript I am used to just being able to pick any character from a string like "exm[2]" and it would return to me the third character in a string. In C is there a way to do that or something without a function that requires a buffer?

+6  A: 

Since in C "strings" are just character arrays, you can do the same there, too:

char* foo = "Hello World";
printf("%c", foo[4]); // prints o

More to the point, a "string" is just a pointer pointing to the first element of an array of characters ending with a zero character ('\0'). String functions just iterate until they find that null character (which is why they have fun when it's not there) and indexing into an array is just a fancy way of writing some pointer arithmetic:

foo[4]

turns into

*(foo + 4)
Joey
How would I get the 1 character I want without a terminating byte right after it?
Jay
@Jay: You already do. *strings* have null terminators. *characters* do not.
Artelius
+1 That's the answer. You don't need any more except to add that strings are indexed from 0, as I am sure that you know. And, if you want to look deeply into it, [] is just a form of pointer referencing.
LeonixSolutions
@Leo: added just that now :)
Joey
Okay, thanks that helped a lot. Reminded me about sscanf().
Jay
There's one thing you need to add, which is in C you have to be careful not to ask for a character outside the bounds of the string: `if (strlen(exm) >= 3)` should precede an attempt to access `exm[2]`, unless you can otherwise prove that the string must be at least that long at that point in the program.
caf