I want to print every other word in a sentence/string. And in the output, first letter should be in upper case.
Example:
Enter a string: Hello how are you doing today?
The resulting string is:
How you today?
This is the code I have tried. It is working fine but I wanted to improve the code. Please let me know what are the improvements that can be made in the code. I have not worked with StringBuilder much. So, I wanted to write the code using it or if I can write the code using different functions.
Thanks in advance.
import java.util.*;
public class Main{
public String skipWords(String str){
String a ="";
String[] wordsArr = str.split(" ");
for(int i = 0 ; i< wordsArr.length; i++){
if(i%2 != 0)
a= a+wordsArr[i] + " ";
else
a = a.replace(wordsArr[i]," ");
}
return a;
}
public String fCapital(String str){
String f = str.substring(0, 1);
String r = str.substring(1);
f = f.toUpperCase();
String c = f + r;
return c;
}
public static void main(String[] args){
String result = "";
Main obj = new Main();
Scanner sc= new Scanner(System.in);
System.out.print("Enter a string: ");
String str= sc.nextLine();
String w = obj.skipWords(str);
result = obj.fCapital(w);
System.out.println("The resulting string is: ");
System.out.println(result);
}
}