-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmashWords.java
More file actions
27 lines (24 loc) · 1.23 KB
/
SmashWords.java
File metadata and controls
27 lines (24 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//8th kyu
//Write a method that takes an array of words and smashes them together into a sentence and returns the sentence.
//You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word.
//Be careful, there shouldn't be a space at the beginning or the end of the sentence!
//Example: ['hello', 'world', 'this', 'is', 'great'] => 'hello world this is great'
import java.util.Arrays;
public class SmashWords {
public static String smash(String... words) {
// TODO Write your code below this comment please
if (words.length == 0 || words == null){ //checks if empty array or null
return ""; //returns empty string
}
int n = words.length; //array's length
String newString = words[0]; //ensures newString starts with the first word
String spaces = " "; //space used to seperate words
for (int i = 1; i < n; i++){ //starts at 1 because the first word is already part of newString
newString += spaces + words[i]; //adds a space and the next word in the array to newString
}
return newString; //returns newString
}
public static void main(String[] args){
System.out.println(smash("hello", "my", "name", "is", "haani")); //test
}
}