I am attempting to split a String into 2 separate Strings, one from the first letter up until a tab, and the other beginning after the tab and ending at the end of the String. I have looked over this post and have found my problem to be different. I am currently trying to utilize the split() method, but with no luck. My code is as follows:
Scanner loadFile = new Scanner(System.in);
loadFile = new Scanner(menuFile);
//loops through data and adds into the SSST
while(loadFile.hasNextLine()){
String line = loadFile.nextLine();
String[] thisLine = line.split(" ");
System.out.println(thisLine[0]);
String item = thisLine[0];
String value = thisLine[1];
menu.put(item, value);
I run into my problem at the line line.split(" "); because I do not know the argument to provide to this method in order to split at the tab in my String.
menu in this code is a separate object and is irrelevant.
Sample input for this program:
"baguette 400"
Desired output for this program:
String 1: "baguette"
String 2: "400"
The tab character is written \t. The code for splitting the line thus looks like this:
String[] thisLine = line.split("\t");
More flexible, if feasible for your use case: For splitting on generic white space characters, including space and tab use \\s (note the double reversed slash, because this is a regex).
Related
I know pipe is a special character and I need to use:
Scanner input = new Scanner(System.in);
String line = input.next();
String[] columns = line.split("\\|");
to use the pipe as a delimiter. But it doesn't work as desired when I parse from the command line.
e.g.
When I parse from a file, this just works. However, when the input has a white space, whenever I parse the input from command line, it gives me out of bounds error, because it splits the word into two array element.
input
a|5|Hello|3
output:
columns[0] = "a";
columns[1] = "5";
columns[2] = "Hello";
columns[3] = "3";
bug:
input:
a|5|Hello World|3;
output:
columns[0] = "a";
columns[1] = "5";
columns[2] = "Hello";
columns[3] = "World";
columns[4] = "3";
I want columns[3] as "Hello World". How can I fix this?
I think you should get the data from user by using nextLine() instead of only next().
In my case its working fine just click here and check the source code ..
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. nextLine() reads input including space between the words (that is, it reads till the end of line n).
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. Source
To overcome, you should use nextline() method instead.
String line = input.nextline();
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.
I am trying to implement a way for taking in arguments for a photo album that I am building. However, I am having a hard time figuring out how to tokenize the input.
Two sample inputs:
addPhoto "DSC_017.jpg" "DSC_017" "Fall colors"
addPhoto "DSC_018.jpg" "DSC_018" "Colorado Springs"
I would like this input to return a String array containing 4 elements where
String s[1]="addPhoto"
String s[2]="DSC_017.jpg"
String s[3]="DSC_017"
String s[4] = "Fall colors"
I looked into StringTokenizer and String.split but I'm not sure how to go about setting the delimiters.
String line = "addPhoto \"DSC_018.jpg\" \"DSC_018\" \"Colorado Springs\"";
String[] pieces = line.split(" \"");
for (String p : pieces) {
System.out.println(p.replaceAll("\"", ""));
}
You might want to pull these arguments off the command line args, the shell will do the quote handling for you. However, you'll only be able to do one addPhoto operation at a time.
If you can't do that, you might try one of these answers:
http://www.source-code.biz/snippets/java/5.htm
Parsing quoted text in java
Split a quoted string with a delimiter
Tokenizing a String but ignoring delimiters within quotes
I got a string with a bunch of numbers separated by "," in the following form :
1.2223232323232323,74.00
I want them into a String [], but I only need the number to the right of the comma. (74.00). The list have abouth 10,000 different lines like the one above. Right now I'm using String.split(",") which gives me :
System.out.println(String[1]) =
1.2223232323232323
74.00
Why does it not split into two diefferent indexds? I thought it should be like this on split :
System.out.println(String[1]) = 1.2223232323232323
System.out.println(String[2]) = 74.00
But, on String[] array = string.split (",") produces one index with both values separated by newline.
And I only need 74.00 I assume I need to use a REGEX, which is kind of greek to me. Could someone help me out :)?
If it's in a file:
Scanner sc = new Scanner(new File("..."));
sc.useDelimiter("(\r?\n)?.*?,");
while (sc.hasNext())
System.out.println(sc.next());
If it's all one giant string, separated by new-lines:
String oneGiantString = "1.22,74.00\n1.22,74.00\n1.22,74.00";
Scanner sc = new Scanner(oneGiantString);
sc.useDelimiter("(\r?\n)?.*?,");
while (sc.hasNext())
System.out.println(sc.next());
If it's just a single string for each:
String line = "1.2223232323232323,74.00";
System.out.println(line.replaceFirst(".*?,", ""));
Regex explanation:
(\r?\n)? means an optional new-line character.
. means a wildcard.
.*? means 0 or more wildcards (*? as opposed to just * means non-greedy matching, but this probably doesn't mean much to you).
, means, well, ..., a comma.
Reference.
split for file or single string:
String line = "1.2223232323232323,74.00";
String value = line.split(",")[1];
split for one giant string (also needs regex) (but I'd prefer Scanner, it doesn't need all that memory):
String line = "1.22,74.00\n1.22,74.00\n1.22,74.00";
String[] array = line.split("(\r?\n)?.*?,");
for (int i = 1; i < array.length; i++) // the first element is empty
System.out.println(array[i]);
Just try with:
String[] parts = "1.2223232323232323,74.00".split(",");
String value = parts[1]; // your 74.00
String[] strings = "1.2223232323232323,74.00".split(",");
I'm trying to split paragraphs of information from an array into a new one which is broken into individual words. I know that I need to use the String[] split(String regex), but I can't get this to output right.
What am I doing wrong?
(assume that sentences[i] is the existing array)
String phrase = sentences[i];
String[] sentencesArray = phrase.split("");
System.out.println(sentencesArray[i]);
Thanks!
It might be just the console output going wrong. Try replacing the last line by
System.out.println(java.util.Arrays.toString(sentencesArray));
The empty-string argument to phrase.split("") is suspect too. Try passing a word boundary:
phrase.split("\\b");
You are using an empty expression for splitting, try phrase.split(" ") and work from there.
This does nothing useful:
String[] sentencesArray = phrase.split("");
you're splitting on empty string and it will return an array of the individual characters in the string, starting with an empty string.
It's hard to tell from your question/code what you're trying to do but if you want to split on words you need something like:
private static final Pattern SPC = Pattern.compile("\\s+");
.
.
String[] words = SPC.split(phrase);
The regex will split on one or more spaces which is probably what you want.
String[] sentencesArray = phrase.split("");
The regex based on which the phrase needs to be split up is nothing here. If you wish to split it based on a space character, use:
String[] sentencesArray = phrase.split(" ");
// ^ Give this space