public static String[] wordList(String line){
Scanner scanner = new Scanner(line);
String[] words = line.split(" ");
for( int i=0; i<words.length; i++)
{
String word = scanner.next();
return words[i] = word;
}
scanner.close();
}
On the line return words[i] = word; I get the error message saying "cannot convert String to String[]". Help?
line.split() already gives you an array, you just need to return that:
public class Test {
public static String[] wordList(String line){
return line.split(" ");
}
public static void main(String args[]) {
String xyzzy = "paxdiablo has left the building";
String[] arr = wordList(xyzzy);
for (String s: arr)
System.out.println(s);
}
}
Running that gives:
paxdiablo
has
left
the
building
Keep in mind that's for one space between each word. If you want a more general solution that uses a separator of "any amount of whitespace", you can use this instead:
public static String[] wordList(String line){
return line.split("\\s+");
}
The regular expressions that you can use with String.split() can be found here.
String[] words = line.split(" ");
Is all you need. The split() method already returns an array of Strings.
Assuming you're trying to split by spaces, you're method should look like:
public static String[] wordList(String line){
return line.split(" ");
}
Related
I have the following code which is my attempt:
public static void main(String[] args) {
String sample = "The quick brown fox";
System.out.println(highestRanking(sample));
}
public static String highestRanking(String sentence){
String[] words = sentence.split(" ");
String highestWord = "";
int biggestASCIIValue = 0;
for (String word : words){
if (word.chars().sum() > biggestASCIIValue){
highestWord = word;
}
}
return highestWord;
}
For some reason the sum of word chars is giving me zero. I found this method here.
Any ideas why my code doesn't seem to work?
Thank you
Stream API offers Stream::max accepting a custom Comparator:
public static String highestRanking(String sentence){
return Arrays.stream(sentence.split("\\s+"))
.max(Comparator.comparingInt(word -> word.chars().sum()))
.orElse(null);
}
I'd like to reverse a string word by word except the last letter of each word.
For example: "Hello how are you" -> lleHo ohw rae oyu
but I am getting output as: olleH woh era uoy
I'm not able to fix the last letter of each word.
This is my Java code for the above output:
public class Main
{
public static void main(String[] args) {
String s = "Hello how are you ";
char [] ch = s.toCharArray();
System.out.println(ch.length);
int pos=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]==' ')
{
for(int j=i;j>=pos;j--)
{
System.out.print(ch[j]);
}
pos=i+1;
}
}
}
}
Below is the solution to solve the problem:
public class Main {
public static void main(String[] args) {
//call the reverseSentence Method
reverseSentence("Hello how are you");
}
public static void reverseSentence(String sentence) {
//Replacing multiple space with a single space
sentence = sentence.replaceAll("[ ]{2,}", " ");
//Split the array and store in an array
String [] arr = sentence.split(" ");
StringBuilder finalString = new StringBuilder();
//Iterate through the array using forEach loop
for(String str : arr) {
//Creating substring of the word, leaving the last letter
String s = str.substring(0, str.length() - 1);
//Creating StringBuilder object and reversing the String
StringBuilder sb = new StringBuilder(s);
//Reversing the string and adding the last letter of the work again.
s = sb.reverse().toString() + str.charAt(str.length() - 1);
//Merging it with the final result
finalString.append(s).append(" ");
}
//Printing the final result
System.out.println(finalString.toString().trim());
}
}
What I have done is, firstly split all the words on spaces and store it inside an array. Now iterate through the array and get the substring from each word leaving the last letter of each word. And then I am using StringBuilder to reverse the String. Once that is done I am adding the last letter of the word to the reversed string and merging it with the finalString which is created.
I'd use regex replaceAll with a lambda to handle the reversal. \S+ matches any sequence of non-space characters. This has the advantage of elegantly handling arbitrary whitespace. You could use \w+ if you want to avoid reversing punctuation characters, although matching words like "isn't" and so forth suggests the problem devolves into natural language processing. I assume your specification is not so complex, though.
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
String res = Pattern
.compile("\\S+")
.matcher("Hello how are you")
.replaceAll(m -> {
String s = m.group();
return new StringBuilder(s.substring(0, s.length() - 1))
.reverse().toString() + s.charAt(s.length() - 1);
});
System.out.println(res); // => lleHo ohw rae oyu
}
}
How do you think of this solution?
public class Main
{
public static void main(String[] args) {
String s = "Hello how are you ";
char [] ch = s.toCharArray();
System.out.println(ch.length);
int pos=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]==' ')
{
System.out.print(ch[i]);
for(int j=i-2;j>=pos;j--)
{
System.out.print(ch[j]);
}
System.out.print(ch[i-1]);
pos=i+1;
}
}
}
}
public class Main {
public static void main(String[] args) {
String s = "Hello how are you ";
final List<String> list = Arrays.asList(s.split(" "));
StringBuilder builder = new StringBuilder();
list.forEach(item ->{
StringBuilder itemBuilder = new StringBuilder(item);
final String rStr = itemBuilder.reverse().toString();
builder.append(rStr.substring(1,rStr.length())).append(rStr.substring(0,1)).append(" ");
});
System.out.println(builder.toString());
}
}
FP style:
String str = "Hello how are you";
String res = Arrays.stream(str.split(" "))
.map(s ->
new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString() + s.substring(s.length() - 1)
)
.reduce((s, s1) -> s + " " + s1)
.orElse("");
System.out.println(res); // lleHo ohw rae oyu
A simpler solution would be to just use the Java Stack data structure for each word (after a string.split) and just add each letter (except token.length-1).
public static void main(String[] args) {
String string = "Hello how are you ";
final String[] tokens = string.split(" ");
for (String token : tokens) {
final Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < token.length()-1; i++) {
stack.push(token.charAt(i));
}
while (!stack.empty()) {
System.out.print(stack.pop());
}
System.out.print(token.charAt(token.length()-1) + " ");
}
}
I need to pass the String in the end of method in order to print String directly in main method, but when I did below, I receive just this one
[Ljava.lang.String;#135fbaa4
public static String businessLogic(String[] words) {
for (String word : words) {
char[] arrayWordInChar = word.toCharArray();
int wordLength = word.length();
for (int i = 0, j = wordLength - 1; i < j; ) {
if (!Character.isAlphabetic(arrayWordInChar[i]))
i++;
else if (!Character.isAlphabetic(arrayWordInChar[j]))
j--;
else
swapLetters(arrayWordInChar, i++, j--);
}
arrayWordInChar.toString();
}
return Arrays.toString(words);
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] words = scanner.nextLine().split(" ");
businessLogic(words);
System.out.println(words);
}
}
I have been confused with this question for almost 2 days, what's the problem?
You get "[Ljava.lang.String;#135fbaa4" because words is String[], you can change the code as below.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] words = scanner.nextLine().split(" ");
//businessLogic(words);
System.out.println(businessLogic(words));
}
Arrays.toString(str)
String Constructor
String.valueOf() or String.copyValueOf()
First, add assignment to words array by words = businessLogic(words);
To print your arraylist elements, you can do one of the following :
System.out.println(Arrays.toString(words));
or
for(String word : words){
System.out.println(word);
}
businessLogic method returns a string but you are not assigning it to any String variable and in your System.out you are printing array words as a string.
System.out.println(businessLogic(words));
above line will print your desired output.
I am not sure what to do, I have found all this online and I am trying to change it to do what I explained above but I am stuck. Basically what I want to do is copy and paste an essay into the code somewhere, the have it look through the essay for any words i tell it to look for, and if it finds them then to replace it with the word or words I want it to.
/**
*
import java.util.Arrays;
public class Main {
public static String[] wordList(String line){
return line.split(" ");
}
public static void main(String args[]) {
String words = "test words tesing";
String[] arr = wordList(words);
for(words i=0; i<words.length; i++)
for (String s: arr)
System.out.println(s);
}
}
*/
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main ( String args[] ){
String[] sEnterWord = getSortedWordArr();
showWordlist(sEnterWord);
String sWordToChange = getInputFromKeyboard("Which word would you like to change? ");
System.out.println("You have chosen to change the word : " + sWordToChange);
changeWordInArray(sWordToChange, sEnterWord);
Arrays.sort(sEnterWord);
showWordlist(sEnterWord);
}
private static String[] getSortedWordArr(){
String line = getInputFromKeyboard("How many words are you going to enter? ");
int length = Integer.valueOf(line);
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
sEnterWord[nCtr] = getInputFromKeyboard("Enter word " + (nCtr+1) + ":");
}
Arrays.sort(sEnterWord);
return sEnterWord;
}
private static String getInputFromKeyboard(String prompt){
System.out.print(prompt);
Scanner s = new Scanner(System.in);
String input = s.nextLine();
return input;
}
private static void showWordlist(String[] words){
System.out.println("Your words are: ");
for (String w : words){
System.out.println(w);
}
}
private static void changeWordInArray(String word, String[] array){
String newWord = getInputFromKeyboard("Enter the new word: ");
for (int i = 0; i < array.length; i++){
if (array[i].equals(word)){
array[i] = newWord;
break;
}
}
Arrays.sort(array);
}
}
To read from the keyboard use
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader (isr);
String cadena = br.readLine();
And all the words you introduced form the keyboard will be in "cadena".
To separte all the words you introduced you could use the method split from String.class.
String[] words = cadena.split(" ");
To find a specific word you could use a method and the code would be in your method would be:
String yourWord = "";
for(int i = 0; i < words.length; i++)
{
if(words[i].equals("your word"))
{
yourWord = words[i];
break;
}
}
To replece a word use the method replce(theWord, "the replacement")
You can prints all the words using a loop for with System.out.println(yourWord);
I have a string with several words separated by spaces, e.g. "firstword second third", and an ArrayList. I want to split the string into several pieces, and add the 'piece' strings to the ArrayList.
For example,"firstword second third" can be split to three separate strings , so the ArrayList would have 3 elements; "1 2 3 4" can be split into 4 strings, in 4 elements of the ArrayList. See the code below:
public void separateAndAdd(String notseparated) {
for(int i=0;i<canBeSepartedinto(notseparated);i++{
//what should i put here in order to split the string via spaces?
thearray.add(separatedstring);
}
}
public int canBeSeparatedinto(String string)
//what do i put here to find out the amount of spaces inside the string?
return ....
}
Please leave a comment if you dont get what I mean or I should fix some errors in this post. Thanks for your time!
You can split the String at the spaces using split():
String[] parts = inputString.split(" ");
Afterwards iterate over the array and add the individual parts (if !"".equals(parts[i]) to the list.
If you want to split on one space, you can use .split(" ");. If you want to split on all spaces in a row, use .split(" +");.
Consider the following example:
class SplitTest {
public static void main(String...args) {
String s = "This is a test"; // note two spaces between 'a' and 'test'
String[] a = s.split(" ");
String[] b = s.split(" +");
System.out.println("a: " + a.length);
for(int i = 0; i < a.length; i++) {
System.out.println("i " + a[i]);
}
System.out.println("b: " + b.length);
for(int i = 0; i < b.length; i++) {
System.out.println("i " + b[i]);
}
}
}
If you are worried about non-standard spaces, you can use "\\s+" instead of " +", as "\\s" will capture any white space, not just the 'space character'.
So your separate and add method becomes:
void separateAndAdd(String raw) {
String[] tokens = raw.split("\\s+");
theArray.ensureCapacity(theArray.size() + tokens.length); // prevent unnecessary resizes
for(String s : tokens) {
theArray.add(s);
}
}
Here's a more complete example - note that there is a small modification in the separateAndAdd method that I discovered during testing.
import java.util.*;
class SplitTest {
public static void main(String...args) {
SplitTest st = new SplitTest();
st.separateAndAdd("This is a test");
st.separateAndAdd("of the emergency");
st.separateAndAdd("");
st.separateAndAdd("broadcast system.");
System.out.println(st);
}
ArrayList<String> theArray = new ArrayList<String>();
void separateAndAdd(String raw) {
String[] tokens = raw.split("\\s+");
theArray.ensureCapacity(theArray.size() + tokens.length); // prevent unnecessary resizes
for(String s : tokens) {
if(!s.isEmpty()) theArray.add(s);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for(String s : theArray)
sb.append(s).append(" ");
return sb.toString().trim();
}
}
I would suggest using the
apache.commons.lang.StringUtils library.
It is the easiest and covers all the different conditions you can want int he spliting up of a string with minimum code.
Here is a reference to the split method :
Split Method
you can also refer to the other options available for the split method on the same link.
Do this:
thearray = new ArrayList<String>(Arrays.asList(notseparated.split(" ")));
or if thearray already instantiated
thearray.addAll(Arrays.asList(notseparated.split(" ")));
If you want to split the string in different parts, like here i am going to show you that how i can split this string 14-03-2016 in day,month and year.
String[] parts = myDate.split("-");
day=parts[0];
month=parts[1];
year=parts[2];
You can do that using .split() try this
String[] words= inputString.split("\\s");
try this:
string to 2 part:
public String[] get(String s){
int l = s.length();
int t = l / 2;
String first = "";
String sec = "";
for(int i =0; i<l; i++){
if(i < t){
first += s.charAt(i);
}else{
sec += s.charAt(i);
}
}
String[] result = {first, sec};
return result;
}
example:
String s = "HelloWorld";
String[] res = get(s);
System.out.println(res[0]+" "+res[1])
output:
Hello World