Computer Science, asked by parvez13, 1 year ago

write a program in Java to accept a string and display each word in separate lines

Answers

Answered by Incredible29
10
Heya user ,
Here is your answer !!

________________________

## USING SUBSTRING FUNCTION ##

import java.util.*;
public class Word
{
public static void main ( String args [] )
{
Scanner in = new Scanner ( System.in ) ;
System.out.print ( " Enter a string : " ) ;
String S = in.nextLine();
int k = 0 ;
S = S + " " ;
for ( int i = 0 ; i < S.length() ; i++ )
{
char ch = S.charAt ( i ) ;
if ( ch == ' ' )
{
String St = S.substring( k , i ) ;
System.out.println ( St ) ;
k = i + 1 ;
}
}
}
}

________________________

## WITHOUT USING SUBSTRING FUNCTION ##

import java.util.*;
public class Word
{
public static void main ( String args [] )
{
Scanner in = new Scanner ( System.in ) ;
System.out.print ( " Enter a string : " ) ;
String S = in.nextLine();
S = S + " " ;
String N = "";
for ( int i = 0 ; i < S.length() ; i ++ )
{
if ( S.charAt( i ) != ' ' )
N = N + S.charAt ( i ) ;
else
{
System.out.println ( N ) ;
N = "" ;
}
}
}
}

________________________

** INPUT :
Sky is blue

** OUTPUT :
Sky
is
blue

Hope it helps you !!

Incredible29: if there is no blank space ... then we accumulate the characters in N
Incredible29: if there is a blank space ... we go the else part and print whatever is there in N
Incredible29: n then make N empty again by declaring it as ""
parvez13: Brilliant...
parvez13: fantastic
parvez13: overwhelming
parvez13: magnificent
parvez13: I could use a lot more of synonyms to thank u....
Incredible29: haha ... thnx a lot :)
parvez13: hey can u help me with a program to count the no. of words in a string
Similar questions