write a program in Java to accept a string and count how many words are there
Answers
Answered by
7
Heya user ,
Here is your answer !!
______________________
import java.util.*;
public class Words
{
public static void main ( String args [] )
{
Scanner in = new Scanner ( System.in ) ;
System.out.print ( " Enter a sentence : " ) ;
String S = in.nextLine() ;
S = S.trim();
int k = 1 ;
for ( int i = 0 ; i < S.length() ; i++ )
{
if ( S.charAt( i ) = ' ' )
k++ ;
}
System.out.println ( " No. of words : " + k ) ;
}
}
______________________
EXPLANATION :
☆ S is the actual string .
☆ Now , we trim the string so that all the extra spaces at the beginning and at the end are removed .
☆ The ' for ' loop count the number of blank spaces in the string .
☆ The no. of blank spaces is stored in the variable k .
☆ NOTE :
THE NO. OF WORDS IN A STRING IS ALWAYS = ( NO. OF SPACES + 1 ) .
☆ So , we have initialised the value of k as 1 .
______________________
** INPUT :
I love computer
** OUTPUT :
3
Hope it helps you !!
Here is your answer !!
______________________
import java.util.*;
public class Words
{
public static void main ( String args [] )
{
Scanner in = new Scanner ( System.in ) ;
System.out.print ( " Enter a sentence : " ) ;
String S = in.nextLine() ;
S = S.trim();
int k = 1 ;
for ( int i = 0 ; i < S.length() ; i++ )
{
if ( S.charAt( i ) = ' ' )
k++ ;
}
System.out.println ( " No. of words : " + k ) ;
}
}
______________________
EXPLANATION :
☆ S is the actual string .
☆ Now , we trim the string so that all the extra spaces at the beginning and at the end are removed .
☆ The ' for ' loop count the number of blank spaces in the string .
☆ The no. of blank spaces is stored in the variable k .
☆ NOTE :
THE NO. OF WORDS IN A STRING IS ALWAYS = ( NO. OF SPACES + 1 ) .
☆ So , we have initialised the value of k as 1 .
______________________
** INPUT :
I love computer
** OUTPUT :
3
Hope it helps you !!
siddhartharao77:
Nice. But next times write the output also..
Similar questions