write a program in Java to accept a string and display each word in separate lines
Answers
Answered by
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 !!
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
Similar questions
Social Sciences,
7 months ago
English,
7 months ago
Math,
1 year ago
English,
1 year ago
Chemistry,
1 year ago