Write a java program to find the first and last word in the sentence

Write a java program to find the first and last word in the sentence. Write a program to read a string containing multiple words find the first and last words, if they are same, return the length and if not return the sum of length of the two words.

The return type is the length as per problem.

Create a Class Main which would be used to accept the string and call the static method present in UserMainCode.

Input and Output Format:

Input consists of a string.
Output consists of a integer.
Refer sample output for formatting specifications.

Sample Input 1:
This is demo demo

Sample Output 1:
4

Sample Input 2:
Hello World Hello

Sample Output 2:
5

java program to find the first and last word in the sentence

import java.util.*;
 
public class Main {
 
 
public static void main(String[] args)  {
// TODO Auto-generated method stub
String s1="this is demo demo";
List<String> l=new ArrayList<String>();
StringTokenizer t=new StringTokenizer(s1," ");
while(t.hasMoreTokens())
{
String s2=t.nextToken();
l.add(s2);
}
String s3=l.get(0);
String s4=l.get(l.size()-1);
if(s3.equals(s4))
{
int n=s3.length();
System.out.println(n);
}
else
{
int n1=s3.length();
int n2=s4.length();
System.out.println(n1+n2);
}
}
}

Add a Comment

Your email address will not be published. Required fields are marked *

twelve + one =