In: Computer Science
Create a method named stringOperations () that accepts a string variable.
This method must perform the following operations:
Split the sentence into an array
Display each element in the array on a seprate line using “ForEach”
Print the first element in the array, using the array syntax
Tell the user where the second word starts
Display the first 3 characters of the second word
In your man method, ask the user to enter a sentence of 5 words. Catch any errors.
Invoke the method StringOperation () passing what was entered as an argument.
import java.util.*;
public class Main
{
static void StringOperation(String s)
{
String t;
String []r=s.split(" ");
if(r.length!=5)//if it not a length
of 5
{
//return back
System.out.println("enter sentence
with 5 words");
return;
}
//using for each loop
for(String p:r)
{
System.out.println(p);
}
//first value of sentence using
index 0
System.out.println(r[0]);
//we can find index of second word
on sentence using indexOf
int index=s.indexOf(r[1]);
System.out.println("The second word
found at "+index);
//we can use substring to print
first n characters
System.out.println("the first 3
characters of second word is "+r[1].substring(0,3));
}
public static void main(String[] args) {
String s,t;
System.out.println("Enter the
sentence with 5 words");
Scanner in=new
Scanner(System.in);
s=in.nextLine();
StringOperation(s);
}
}