-1

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);   
    }
}
bug24
  • 7
  • 2
  • 2
    *"...but I wanted to improve the code"* -- improve the code ***how***? Please be specific about exactly what it is you're asking. – Hovercraft Full Of Eels Sep 03 '21 at 11:48
  • 1
    If your code is working as intended, but you are looking for ways to improve it, https://codereview.stackexchange.com/ might be suitable for your question. – Hulk Sep 03 '21 at 11:59
  • You might not want to concadate strings with `+` in loops. – dan1st Sep 03 '21 at 12:02
  • can you explain more ?? – S.Sachith Sep 03 '21 at 12:04
  • I'm not sure what you were trying to do with a = a.replace(wordsArr[i]," ");, but I think you will find that 1) your programs works quite well without it 2) if your input is something like "abc abc abc abc abc" your output will be nothing because of that line. – Gonen I Sep 03 '21 at 12:17
  • @Hulk Thank you will try that. – bug24 Sep 04 '21 at 17:08
  • @HovercraftFullOfEels I have not worked with StringBuilder much. So, I wanted to write the code using it. – bug24 Sep 04 '21 at 17:14
  • And where do you mention this fact in your question? – Hovercraft Full Of Eels Sep 04 '21 at 17:23
  • @HovercraftFullOfEels Sorry, will keep that in mind in future. I just wanted to know others ways of writing the code. – bug24 Sep 04 '21 at 17:32
  • 2
    Good, glad that you plan to keep this in mind. In general "please give me other/better ways of writing this code" type questions are closed and eventually deleted for being too broad or being unclear. This won't affect you in the short term, but in the longer term it might, since if enough of your questions are felt to be low-quality, the site will automatically ban you from asking questions, even if you create a new user identity, something that you will want to avoid happening. Even moderators can't reverse this ban. Good luck in your coding career and education. – Hovercraft Full Of Eels Sep 04 '21 at 17:35
  • @HovercraftFullOfEels Okay will definitely correct it and thank you so much!! – bug24 Sep 04 '21 at 20:00

3 Answers3

1

Take a look:

public String skipWords(String sentence) {
    String[] words = sentence.split(" ");
    StringBuilder result = new StringBuilder();

    for (int i = 1; i < words.length + 1; i += 2) {
        result.append(words[i]).append(" ");
    }
    return result.toString();
}
  • Meaningful variable names.
  • StringBuilder instead of + operator.
lkatiforis
  • 5,703
  • 2
  • 16
  • 35
  • Thank you so much. This is what I wanted to learn. I have not worked much with StringBuilder – bug24 Sep 04 '21 at 17:00
1

I think you can try this below one and reduce so many lines and also calling the static methods which costs a lot

String str = sc.nextLine();
String removefirst = (str.split(" ",2)[1]);
String finalVal = removefirst.substring(0, 1).toUpperCase() + removefirst.substring(1);

and the output will look like this,

Enter a string: league of legends
Of legends

in the removeFirst variable will take the String with first word removed and then in the finalVal variable will contain the string with first letter capital, if you want to reduce variables as well you can merge those two in to one and use it.

  • Thank you! But I want the output to be `Of` only. Like if a sentence is - **the quick brown fox jumps over the lazy dog.** I want the output to be - `Quick fox over lazy` – bug24 Sep 04 '21 at 17:06
0

One improvement you can make in your code is to remove this line:

                else 
                    a = a.replace(wordsArr[i]," ");

It serves no real purpose, and can actually lead to wrong results by erasing a skipped word which also happens to be a non skipped word that was added previouisly. For example the input "abc abc abc abc abc" will be reduced to nothing.

The points raised by the other answers such as meaningful names and using StringBuilder to build strings more efficiently are also valid.

Finally, as an alternative you can also use Streaming APIs, this example requires Java 9.

public String skipWords(String str){
     String[] list = str.split(" ");
     String result = Stream.iterate(1, i->i+2).takeWhile(i-> i<list.length).map(i->list[i]).collect(Collectors.joining( " " ));
     return result;
}

It splits the String into an array, then uses Stream.iterate to build a stream of the numbers 1,3,5,7,... etc and then uses takeWhile to limit that stream to the length of the array. The map function takes each other word e.g. by turning 1 into list[1], and the collect function joins them all into one string.

With Java 11, the iteration can be shortened to

     String result = Stream.iterate(1, i->i<list.length,i->i+2).map(i->list[i]).collect(Collectors.joining( " " ));
Gonen I
  • 5,576
  • 1
  • 29
  • 60