Split a string you’ve entered with scanner - java

I have a problem. I want to type in a string (with Java.util.scanner) with two words. Then I want the program to split my entered string at the whitespace, save both substrings in a seperate variable and make a output in the end.
I know that you can split strings with
String s = "Hello World";
String[] = s.split(" ");
But it doesnt seem to work when your String is
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
Any help?
Thank you very much

s.split("\\s+"); will split your string, even if you have multiple whitespace characters (also tab, newline..)
You can also use from java.util package
StringTokenizer tokens = new StringTokenizer(s.trim());
String word;
while (tokens.hasMoreTokens()) {
word = tokens.nextToken();
}
Or from Apache Commons Lang
StringUtils.split(s)

Your code works for me:
String s;
s=sc.nextLine();
String[] words=s.split(" ");
for(String w:words){
System.out.print(w+" ");
}
input: "Hello world"
output: "Hello world"

You may also want to try this way of splitting String that you get from user input:
Scanner sc = new Scanner(System.in);
String[] strings = sc.nextLine().split("\\s+");
If you simply want to print array containing these separated strings, you can do it without using any loop, simply by using:
Arrays.toString(strings);
If you want to have your printed strings to look other way, you can use for it simple loop printing each element or by using StringBuilder class and its append() method - this way may be faster than looping over longer arrays of strings.

Related

Converting String returned from Scanner nextLine() to String array

My requirement is that I need to convert a string input taken from a Scanner's nextLine() method, to a string array:
My code:
Scanner sc= new Scanner(System.in);
String myString = sc.nextLine();
The above code works fine, when I give input in the console as : new String[]{"A:22","D:3","C:4","A:-22"}
but my challenge is to read scanner input and assign it to String array like this:
String[] consoleInput=sc.nextLine();
I have an incompatible type error, which is normal as String cannot be converted to String array. Is there a way to convert sc.nextLine() to String array in the above line?
If you literally type n, e, w, , S, etcetera (you type in new String[] {"A:22", "D:3"} and you want a method on scanner such that you get a string with that data), that is incredibly complicated and involves linking a java compiler in. If you're asking this kind of question, likely well beyond your current skill level.
What you can do, however, is simply ask the user to enter something like:
A:22 D:3 C:4 A:-22
Simply .nextLine().split(" ") and voila: First read a line, then split that line into a string array by looking for spaces as separators.
Scanner sc = new Scanner(System.in);
String myString = sc.nextLine();
String[] arr = myString.replaceAll("[ \"{}]", "").split(",");
Explanation:
The regex in replaceAll replaces the characters ", {, '}, and ` (space character) with an empty string. Then you simply split the string along all the commas, and you get a String array containing all the tokens the user entered.
Note: the regex removes all spaces as well, so if your tokens have spaces in them, then they will get removed. However, from what I gathered from your question, there won't be any spaces in the elements of the array.
Modified the regex pattern in replaceAll() method :
String[] strArr = s.nextLine().replaceAll("[ \"{}\\]\\[(new|String)]", "").split(",");
Output on printing the String Array strArr:
A:22
D:3
C:4
A:-22

I want to split a string with multiple whitespaces using split() method?

This program is to return the readable string for the given morse code.
class MorseCode{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String morseCode = scanner.nextLine();
System.out.println(getMorse(morseCode));
}
private static String getMorse(String morseCode){
StringBuilder res = new StringBuilder();
String characters = new String(morseCode);
String[] charactersArray = characters.split(" "); /*this method isn't
working for
splitting what
should I do*/
for(String charac : charactersArray)
res.append(get(charac)); /*this will return a string for the
corresponding string and it will
appended*/
return res.toString();
}
Can you people suggest a way to split up the string with multiple whitespaces. And can you give me some example for some other split operations.
Could you please share here the example of source string and the result?
Sharing this will help to understand the root cause.
By the way this code just works fine
String source = "a b c d";
String[] result = source.split(" ");
for (String s : result) {
System.out.println(s);
}
The code above prints out:
a
b
c
d
First, that method will only work if you have a specific number of spaces that you want to split by. You must also make sure that the argument on the split method is equal to the number of spaces you want to split by.
If, however, you want to split by any number of spaces, a smart way to do that would be trimming the string first (that removes all trailing whitespace), and then splitting by a single space:
charactersArray = characters.trim().split(" ");
Also, I don't understand the point of creating the characters string. Strings are immutable so there's nothing wrong with doing String characters = morseCode. Even then, I don't see the point of the new string. Why not just name your parameter characters and be done with it?

.replace to replace input letters with symbols

I want to make everything the user enters capitalized and certain letters to be replaced with numbers or symbols. Im trying to utilize .replace but something is not going right. Im not sure what im doing wrong?
public class Qbert
{
public static void main(String[] args)
{
//variables
String str;
//get input
Scanner kb = new Scanner(System.in);
System.out.print(" Please Enter a Word:");
//accept input
str = kb.nextLine();
System.out.print("" );
System.out.println(str.toUpperCase()//make all letters entered uppercase
//sort specific letters to make them corresponding number, letter, or symbol
+ str.replace("A,#")+ str.replaceChar("E","3")+ str.replaceChar ("G","6")
+ str.replaceChar("I","!")+ str.replaceChar("S","$")+ str.replaceChar ("T","7"));
}
}
In Java, Strings are immutable. This means that modifying a string will result in a new string. E.g.
str.replace("a", "b");
this will replace all the occurrences of 'a' to 'b' in a new string. Original string will remain unaffected. So, to apply the formatting on the actual string, we will have to write:
str = str.replace("a", "b");
Similarly, if we want to do multiple replacements then, we need to append replace calls together, e.g.
str = str.replace("a","b").replace("c", "d");
Going by this, if you want to perform the substitution, the last system.out in your code will be:
System.out.println(str.toUpperCase().replace("A","#").replace("E","3")
.replace("G","6").replace("I","!").replace("S","$").replace("T","7"));
String doesn't have a replaceChar method. You probably wanted to use method replace.
And String.replace() takes 2 arguments:
public String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence. The
replacement proceeds from the beginning of the string to the end, for
example, replacing "aa" with "b" in the string "aaa" will result in
"ba" rather than "ab".
You have written str.replace("A,#")+... instead of str.replace("A","#")+..., and so on
One more thing - use a good IDE like Eclipse or Intellij IDEA, they will highlight the parts of your code where you have errors.
public static void main(String... args) {
// variables
String str;
// get input
Scanner kb = new Scanner(System.in);
System.out.print(" Please Enter a Word:");
// accept input
str = kb.nextLine();
System.out.print("");
System.out.println(str.toUpperCase()); // Upper Case
System.out.println(str.toUpperCase().replace("A", "#").replace("E", "3")
.replace("E", "3").replace("G", "6").replace("I", "!").replace("S", "$").replace("T", "7") );
}
This should work like you want it to. Hope you find this helpful.
As you want to make multiple changes to the same string, you just use
str.toUpperCase().replace().replace().... This means you are giving
the output of str.toUpperCase() to the first replace function and so
on...
System.out.println(str.toUpperCase()
.replace("A","#")
.replace("E","3")
.replace("G","6")
.replace("I","!")
.replace("S","$")
.replace("T","7"));

single string list- alphabetizing

I'm trying to write a code that uses a scanner to input a list of words, all in one string, then alphabetizer each individual word. What I'm getting is just the first word alphabetized by letter, how can i fix this?
the code:
else if(answer.equals("new"))
{
System.out.println("Enter words, separated by commas and spaces.");
String input= scanner.next();
char[] words= input.toCharArray();
Arrays.sort(words);
String sorted= new String(words);
System.out.println(sorted);
}
Result: " ,ahy "
You're reading in a String via scanner.next() and then breaking that String up into characters. So, as you said, it's sorting the single-string by characters via input.toCharArray(). What you need to do is read in all of the words and add them to a String []. After all of the words have been added, use Arrays.sort(yourStringArray) to sort them. See comments for answers to your following questions.
You'll need to split your string into words instead of characters. One option is using String.split. Afterwards, you can join those words back into a single string:
System.out.println("Enter words, separated by commas and spaces.");
String input = scanner.nextLine();
String[] words = input.split(",| ");
Arrays.sort(words);
StringBuilder sb = new StringBuilder();
sb.append(words[0]);
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(words[i]);
}
String sorted = sb.toString();
System.out.println(sorted);
Note that by default, capital letters are sorted before lowercase. If that's a problem, see this question.

Reading text with Java Scanner next(Pattern pattern)

I am trying to use the Scanner class to read a line using the next(Pattern pattern) method to capture the text before the colon and then after the colon so that s1 = textbeforecolon and s2 = textaftercolon.
The line looks like this:
something:somethingelse
There are two ways of doing this, depending on specifically what you want.
If you want to split the entire input by colons, then you can use the useDelimiter() method, like others have pointed out:
// You could also say "scanner.useDelimiter(Pattern.compile(":"))", but
// that's the exact same thing as saying "scanner.useDelimiter(":")".
scanner.useDelimiter(":");
// Examines each token one at a time
while (scanner.hasNext())
{
String token = scanner.next();
// Do something with token here...
}
If you want to split each line by a colon, then it would be much easier to use String's split() method:
while (scanner.hasNextLine())
{
String[] parts = scanner.nextLine().split(":");
// The parts array now contains ["something", "somethingelse"]
}
I've never used Pattern with scanner.
I've always just changed the delimeter with a string.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)
File file = new File("someFileWithLinesContainingYourExampleText.txt");
Scanner s = new Scanner(file);
s.useDelimiter(":");
while (!s.hasNextLine()) {
while (s.hasNext()) {
String text = s.next();
System.out.println(text);
}
s.nextLine();
}

Categories