I am learning C programming and I am trying to print the first letter of each word in a sentence. I have written this code below but it doesn't seem to be working.
#include<stdio.h>
#include<string.h>
int main()
{
char s[100];int i,l;
scanf("%s",&s);
l=strlen(s);
printf("%c",s[0]);
for(i=0;i<l;i++)
{
if(s[i]==' ')
{
printf("%c",s[i+1]);
}
}
}
Input: Hello World
Expected Output: HW
Actual Output: (nothing)
Get the first character of a string in python As indexing of characters in a string starts from 0, So to get the first character of a string pass the index position 0 in the [] operator i.e. It returned a copy of the first character in the string. You can use it to check its content or print it etc.
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. Capitals signal the start of a new sentence. This is a stable rule in our written language: Whenever you begin a sentence capitalize the first letter of the first word.
The problem is in how you're reading the input:
scanf("%s",&s);
The %s
format specifier to scanf
reads characters until it encounters whitespace. This means it stops reading at the first space.
If you want to read a full line of text, use fgets
instead:
fgets(s, sizeof(s), stdin);
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