Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take first letter from C string?

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.

like image 721
user2901857 Avatar asked Oct 21 '13 05:10

user2901857


People also ask

How do you extract the first letter of a string?

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.

How do I get the first letter in C#?

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.

How do you find a specific letter in a string C?

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.

How do you get the first letter of each word in a string?

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.


1 Answers

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.

like image 81
MByD Avatar answered Sep 22 '22 05:09

MByD