Format Words Into A Sentence

format sentence examples
format sentence online
format definition
how to format a sentence in word
sentence structure
example of format
dictionary with example sentences
correct the sentence examples

Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. Empty string values should be ignored. Empty arrays or null/nil values being passed into the method should result in an empty string being returned.

Example:

{"ninja", "samurai", "ronin"}) => "ninja, samurai and ronin"
{"ninja", "", "ronin"}) => "ninja and ronin"

Code

public static String formatWords(String[] words)
    {
        if (words == null || words.length == 0)
        {
            return "";
        }

        String str = "";

        for (int i = 0; i < words.length; i++)
        {
            if (words[i].equals(""))
                continue;
           if (i == words.length - 1)
               str += "and " + words[i];
           else
               str += words[i] + ", ";

        }

        return str;
    }

How can I remove the last comma?

A simple solution would be running the loop in descending order. I have made a few changes to your code.. Hope, this works

public static String formatWords(String[] words)
{
    Vector<String> v= new Vector<String>();
    if (words == null || words.length == 0)
        return "";

    for (int i = 0; i < words.length; i++)
        if (!words[i].equals("")) v.add(words[i]);

    String str="";
    for (int i = v.size()-1; i >= 0; i--)
    {
        if(str.equals("")){
            if(i>0)
                str = " and " + v.get(i);
            else
                str = v.get(i);
        }else{
            if(i==0)
                str = v.get(i) + str;
            else
                str = "," + v.get(i) + str;
        }
    }
    return str;
}

Edit : Made a correction adding Vector for solving the issue @AJNeufeld mentioned in comment

Use formatting in a sentence, How to use formatting in a sentence. Example sentences with the word formatting​. formatting example sentences. The material is in.pdf format (with watermarks) but a simple cut-and-paste into something like Word makes them usable as class notes.

You can use String.join to create the String with the comma. Then replace the last comma with a regex.

String[] values = {"ninja", "samurai", "ronin"};

//Join each values with ", "
String phrase = String.join(", ", values);
System.out.println(phrase); //ninja, samurai, ronin

//Replace the last "," with " and"
phrase = phrase.replaceFirst(",([^,]+)$", " and$1");
System.out.println(phrase); //ninja, samurai and ronin

This is done in a one line :

String phrase = String.join(", ", values).replaceFirst(",([^,]+)$", " and$1");

Using a method for a quick test when can see the result:

public static String createPhrase(String[] values){
    return String.join(", ", values).replaceFirst(",([^,]+)$", " and$1");
}

System.out.println(createPhrase(new String[] {"ninja"} ));
System.out.println(createPhrase(new String[] {"ninja", "samurai"}));
System.out.println(createPhrase(new String[] {"ninja", "samurai", "ronin"}));

ninja ninja and samurai ninja, samurai and ronin

Note:

To manage empty and null values in the array, the easiest is to use a Stream

Stream.of(values)
      .filter(s -> s != null && !s.isEmpty())
      .collect(joining(", "))

Then use the same regex to manage the " and" part.

Format Words Into A Sentence, A simple solution would be running the loop in descending order. I have made a few changes to your code.. Hope, this works public static  Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. Empty string values should be ignored. Empty arrays or null/nil values being passed into the method should result in an empty string being returned. Example:

A common technique is to introduce a "separator" variable. On the first iteration it's the empty string, then most of the time it's ", ", and on the last iteration it's " and ".

It's also best practice to use a StringBuilder when repeatedly appending to a String to avoid repeated (wasteful) memory allocations.

public static String formatWords(String[] words) {
    if (words == null || words.length == 0) {
        return "";
    }
    StringBuilder ans = new StringBuilder();
    for (int i = 0; i < words.length; i++) {
        String sep = ", ";
        if (i == 0)
            sep = "";
        else if (i == words.length - 1)
            sep = " and ";
        ans.append(sep).append(words[i]);
    }
    return ans.toString();
}

Code-Wars/8-format-words-into-a-sentence at master · futurebound , Contribute to futurebound/Code-Wars development by creating an account on GitHub. Complex Sentence Generator is a free content rewriter that can potentially rephrase, reword, paraphrase and/or rewrite sentences, paragraphs, articles, content, words and/or phrases into a more complex, unorthodox or convoluted alternative while delivering the same meaning.

I have a feeling this is a homework assignment, so I'm not going to give you complete solution, but I am going to point you down the correct track, without using advanced concepts like ArrayList<String>, Vector<String>, Stream.of(...) and regular expressions, which likely haven't been taught yet.

The biggest challenge in this assignment is properly skipping over the null/nil values in the words array, and still finding the proper places for the comma separators and the final " and " separator. When looping over the words array, the i == 0 entry does not necessarily mark the first real word, since the array may begin with a null or an empty String. Similarly, the i == words.length-1 entry does not necessarily represent the last word, since the array may end with a null or empty String. The means that the loop index i is practically useless for determining whether a separator is required, and which separator to use.

Since the loop index is more or less useless, we can use the "enhanced for-loop" construct to loop over the words in the array:

for(String word : words) {
    // ... code here
}

If you have not learned the "enhanced for-loop", you can stick with:

for(int i = 0; i < words.length; i++) {
    String word = words[i];
    // ... code here
}

but understand you will not use the value i at any other point inside the loop. As such, I will continue to use the "enhanced for-loop" for the remainder of the discussion, but know it is a simple substitution to change this to a regular for-loop.

The first thing you will need to know is "how many words are there in the words array?" The answer is not words.length because of the possibility of null values and empty String values. The easiest thing to do is count the valid words, using a loop:

int numWords = 0;
for(String word : words) {
    if (word != null  &&  !word.isEmpty()) {
        numWords++;
    }
}

By knowing that there are numWord words, you can now decisively say that the " and " separator goes before the last word, which would be (counting from 1) the numWords-th word.

With this in mind, you can now perform a second loop, which looks at each word, and decides whether or not to treat it as a valid word, and update a wordNumber for valid words only.

String result = "";
int wordNumber = 0;
for(String word : words) {
    if (words != null  &&  !word.isEmpty()) {
        wordNumber++;

        // If not the first word, then add a separator (either a 
        // comma or the word "and" if at the last word) to result.
        // Then, add word to result.
    }
}

I've left out the actual code for the final step of adding the words and the appropriate separator. This is not much different than was done in the initial attempt at solving the problem by the OP, so it should be obvious how to proceed, and yet is not a copy-and-paste-from-Stack-Overflow homework solution. The student does at least some work.


The above solution uses two for loop; the first to count the number of valid words, and the second to process the words. It is often a better to loop over the data exactly once. This allows you to process streams of data, where the data is transient or ephemeral and you may not get a second chance to read the data.

Obviously, this isn't the case in this example. The data is in an array; you can loop over the data as many times as you want. But it is still possible to do the operation using only one loop.

It is more complicated to process the data using one loop. The trick is to hold onto the most recent word, and delay adding it to the result, until you know which separator to use (if any) to add it to the result. When you finish looping over all of the words, you will have a partial result, and the most recent (aka, last) word. At that point, you merely have to add this last word to the result, with the joining word "and", unless it was also the first word.

String result = "";

String most_recent_word = null;
for(String word : words) {
    if (word != null  &&  !word.isEmpty()) {
        if (most_recent_word != null) {
           // Add most_recent_word to result, preceded by a comma if necessary
        }
        most_recent_word = word;
    }
}

if (most_recent_word != null) {
    // Add most_recent_word to result, preceded by " and " if necessary
}

Again, I've left out the critical code of determining if a separator is necessary, and adding it and the most recent word into the result. Again, left to student, to avoid copy-and-paste-from-Stack-Overflow homework solutions.


As mentioned elsewhere, the code efficiency of both the above solutions can be improved using a StringBuilder to build up the final String. It is not required, but if you have been taught how to use it, you should use it!

Complex Sentence Generator, an abundance of rarely used words/phrases and can paraphrase sentences in a Aside from this software being used as a paraphrasing tool, it can also be  Not to mention that formatting a list of words into a sentence in English requires that the first word be capitalized and the last thing in the sentence will be some form of punctuation. The title is misleading.

If you are using Java 8, solution can be simplified as follows:

public static String formatWords(String[] words) {
    String res = Arrays.asList(words)
          .stream()
          .filter(word -> !(word == null))
          .filter(word -> !word.equals(""))
          .collect(Collectors.joining(","));
    if(! res.contains(","))
        return res;

    int indexOfLastComma = res.lastIndexOf(",");

    String resultuntilLastWord = res.substring(0, indexOfLastComma);
    String lastWord = res.substring(indexOfLastComma + 1);

    res = resultuntilLastWord + " and " + lastWord;
    return res;
}

First construct a result String (res in code) with all delimiters as comma.

Then, fetch the index of last comma in string and create two substrings. One substring should be till the last comma in the string:

String resultuntilLastWord = res.substring(0, indexOfLastComma);

and other should be till the end of the string:

String lastWord = res.substring(indexOfLastComma + 1);

Finally merge these two substrings with an " and " in between.

Format, 2 : to prepare (something, such as a computer disk) for storing data in a particular format. Other Words from format Synonyms More Example Sentences Learn  But as you can see, you can use the following formula to force text into sentence case: =UPPER(LEFT(C4,1)) & LOWER(RIGHT(C4,LEN(C4)-1)) If you take a look at this formula closely, you can see that it’s made up of two parts that are joined by the ampersand.

Kata Stats: Format words into a sentence, The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted  Use brackets to enclose inserted words intended to clarify meaning within a quotation. Use parentheses when inserting words into a quotation. Use brackets to enclose inserted words intended to provide a brief explanation within a quotation. Use parentheses to enclose a change in letter case or verb tense when integrating a quote into your paper.

Ginger Software's Sentence Rephraser, With one simple click users can rephrase a sentence with word synonyms, antonyms, idioms and phrases. With Ginger's Sentence Rephraser you'll feel as though  Suppose you want to create a grammatically correct sentence from several columns of data for a mass mailing or format dates with text without affecting formulas that use those dates. To combine text with a date or time, use the TEXT function and the & (ampersand) operator. Example The TEXT function requires two

Change the capitalization or case of text, Select the text you want to change. To capitalize the first letter of a sentence and leave all other letters as lowercase, click Sentence case. To capitalize the first letter of each word and leave the other letters lowercase, click your text, select the text, and then on the Format menu, select Font, and in the Font dialog box,  Use Wordificator to convert your favorite words and quotes into typographic artwork. Wordificator Word Art - Convert Words Into Typographic Art Wordificator .com

Comments
  • Don't put it there to begin with.
  • Advice: read your post and ask yourself if it doesn't sound more like an assignment or demand rather than a question which you have done ample amount of research and effort towards.
  • Consider inverting the issue. Rather than adding a word plus a comma, add a comma, space and word unless it is the last word. Also, consider using StringBuilder rather than building the String. Finally, consider that one can chop off the last two characters by using a .subString() method and the length of the current String minus the appropriate amount.
  • Thank you sir for your advice.
  • Instead of .equals(""), you should use .isEmpty() which internally does something like .length()==0. Personally, in real life I'd make that "if (words[i] == null || words[i].isEmpty())"
  • Results in a leading comma if words starts with an empty string
  • Yes, You are right @AJNeufeld. Changed my code. Thanks
  • Thank you for the solution but I am getting same output as I was getting with my previous code.
  • Give an example? I'm getting the output ninja, samurai and ronin, is this not what you wanted?