I am new to C and I am very much confused with the C strings. Following are my questions.
Finding last character from a string
How can I find out the last character from a string? I came with something like,
char *str = "hello";
printf("%c", str[strlen(str) - 1]);
return 0;
Is this the way to go? I somehow think that, this is not the correct way because strlen
has to iterate over the characters to get the length. So this operation will have a O(n)
complexity.
Converting char
to char*
I have a string and need to append a char to it. How can i do that? strcat
accepts only char*
. I tried the following,
char delimiter = ',';
char text[6];
strcpy(text, "hello");
strcat(text, delimiter);
Using strcat
with variables that has local scope
Please consider the following code,
void foo(char *output)
{
char *delimiter = ',';
strcpy(output, "hello");
strcat(output, delimiter);
}
In the above code,delimiter
is a local variable which gets destroyed after foo
returned. Is it OK to append it to variable output
?
How strcat
handles null terminating character?
If I am concatenating two null terminated strings, will strcat
append two null terminating characters to the resultant string?
Is there a good beginner level article which explains how strings work in C and how can I perform the usual string manipulations?
Any help would be great!