I want to take the first letter from my firstname string variable and add it to the second letter of the lastname variable.
My program so far is:
#include <stdio.h>
main() {
char firstname [256];
char lastname [256];
printf("What's your first name?: ");
scanf("%c",&firstname);
printf("What is your last name? ");
scanf("%s",&lastname);
printf("\nYour school.edu e-mail address is: %c%[email protected]",firstname,lastname);
return 0;
}
However, I would like for my code to take the first initial (the first letter of the first name) and store it into the firstname variable.
Get the First Letter of the String You should use the charAt() method, at index 0, to select the first character of the string. NOTE: charAt is preferable than using [ ] (bracket notation) as str.
To get the first character, use the substring() method. string str = "Welcome to the Planet!"; Now to get the first character, set the value 1 in the substring() method.
Search for a character in a string - strchr & strrchr The strchr function returns the first occurrence of a character within a string. The strrchr returns the last occurrence of a character within a string. They return a character pointer to the character found, or NULL pointer if the character is not found.
To get the first letter of each word in a string: Call the split() method on the string to get an array containing the words in the string. Call the map() method to iterate over the array and return the first letter of each word. Join the array of first letters into a string, using the join() method.
As strings are array of characters, you need to take the first element from the array:
char firstname_initial;
firstname_initial = firstname[0]
Also note that since lastname
and firstname
are buffers, you don't need to pass a pointer to them in scanf
:
scanf( "%s", firstname );
scanf( "%s", lastname );
And one last thing - scanf
is a dangerous function and you should not use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With