Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the first letter of each word in a sentence

Tags:

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)

like image 493
Akash kumar Avatar asked Feb 18 '19 15:02

Akash kumar


People also ask

How do I print the first letter of a word in Python?

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.

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.

What is the first letter of a sentence called?

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.


1 Answers

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);
like image 144
dbush Avatar answered Sep 20 '22 23:09

dbush