Just stuck on c syntax regarding strings.
Say I have a string like (name[5]="peter";) in c say if I just wanted to print the last character of string or check the last character of the string, which in this case would be 'r' how can I do this?
The way I was thinking does not seem to work
name[5]="peter";
if(name[5]=="r") printf("last character of name is r");
Question: is there some sort of function to do this that can check one character of array, is a certain value, like name[5] is ‘r’ in string peter or likewise name[1] is ‘n’
Also how do I use printf to print that certain char, having problems using
printf("last character of name is %s",name[5]) ???
Thanks
First thing, strings are null-terminated. For a five-character string you need to allocate a 6-character array to handle the
'\0'character at the end of the string.To check what individual characters are, index the string using square brackets. The first character is index 0, the second is index 1, etc. Also, C makes a distinction between strings and individual characters. A string is written with
"double quotes". Characters are written with single quotes:'r'.To find the last character you need to know the length of the string. If you know the length ahead of time you can hard code it; otherwise, use the
strlenfunction to calculate the string length. And then subtract 1 because indexes are 0-based.To print individual characters with
printfyou can use the%cformat specifier.%cprints a single character.