Split a string in Java and picking up a part of it - java

Say I got a string from a text file like
"Yes ABC 123
Yes DEF 456
Yes GHI 789"
I use this code to split the string by whitespace.
while (inputFile.hasNext())
{
String stuff = inputFile.nextLine();
String[] tokens = stuff.split(" ");
for (String s : tokens)
System.out.println(s);
}
But I also want to assign Yes to a boolean, ABC to another string, 123 to a int.
How can I pick them up separately? Thank you!

boolean b=tokens[0].equalsIgnoreCase("yes");
String name=tokens[1];
int i=Integer.parseInt(tokens[2]);

Could you clarify what the exact purpose of what you're doing is? You can refer to the separate Strings with tokens[i] with i being the index. You could throw these into a switch statement (since Java 7) and match for the words you're looking for. Then you can take further action, i.e. convert the Strings to Booleans or Ints.
You should consider checking the input to be valid too even if you are expecting the file to always have those 3 words separated by a space.

Create Class Line and List<Line> that will store all your file into list:
public class Line{
private boolean mFlag = false;
private int mNum = 0;
private String mStr;
public Line(String stuff) {
String[] tokens = stuff.split("[ ]+");
if(tokens.length ==3){
mFlag=tokens[0].equalsIgnoreCase("yes");
mNum=Integer.parseInt(tokens[1]);
mStr=tokens[3];
}
}
}
and call it:
public static void main(String[] args) {
List<Line> list = new ArrayList<Line>();
Line line;
while (inputFile.hasNext())
{
String stuff = inputFile.nextLine();
line = new Line(stuff);
list.add(line);
}
}

If your input String is going to be in the same format always i.e. boolean,String ,int then you can access the individual indices of token array and convert them to your specified format
boolean opinion = tokens[0].equalsIgnoreCase("yes");
String temp = token[1];
int i = Integer.parseInt(token[2])
But you might require to create an array or something that stores the values for consecutive inputs that user does otherwise these variables would be over ridden for every new input from user.

Related

Separating an unknown amount of hyphens in java?

Good day, guys,
I'm working on a program which requires me to input a name (E.g Patrick-Connor-O'Neill). The name can be composed of as many names as possible, so not necessarily restricted to solely 3 as seen in the example above.But the point of the program is to return the initials back so in this case PCO. I'm writing to ask for a little clarification. I need to separate the names out from the hyphens first, right? Then I need to take the first character of the names and print that out?
Anyway, my question is basically how do I separate the string if I don't know how much is inputted? I get that if it's only like two terms I would do:
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
I did attempt to do the code, and all I have so far is:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
}
}
}
I'm taking a crash course in programming, so easy concepts are hard for me.Thanks for reading!
You don't need to split it a second time. By doing String[] x = input.split("-"); you have an Array of Strings. Now you can iterate over them which you already do with the enhanced for loop. It should look like this
String[] x = input.split("-");
String initials = "";
for (String name : x) {
initials += name.charAt(0);
}
System.out.println(initials);
Here are some Java Docs for the used methods
String#split
String#charAt
Assignment operator +=
You can do it without splitting the string by using String.indexOf to find the next -; then just append the subsequent character to the initials:
String initials = "" + input.charAt(0);
int next = -1;
while (true) {
next = input.indexOf('-', next + 1);
if (next < 0) break;
initials += input.charAt(next + 1);
}
(There are lots of edge cases not handled here; omitted to get across the main point of the approach).
In your for-each loop append first character of all the elements of String array into an output String to get the initials:
String output = "";
for(String i : x) {
output = output + y.charAt(0);
}
This will help.
public static void main(String[] args) {
String output = "";
String input = "Patrick-Connor-O'Neil-Saint-Patricks-Day";
String[] brokenInput = input.split("-");
for (String temp : brokenInput) {
if (!temp.equals(""))
output = output + temp.charAt(0);
}
System.out.println(output);
}
You could totally try something like this (a little refactor of your code):
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = "";
System.out.println("What's your name?");
input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
System.out.println(y);
}
}
}
I think it's pretty easy and straightforward from here if you want to simply isolate the initials. If you are new to Java make sure you use a lot of System.out since it helps you a lot with debugging.
Good coding.
EDIT: You can use #Mohit Tyagi 's answer with mine to achieve the full thing if you are cheating :P
This might help
String test = "abs-bcd-cde-fgh-lik";
String[] splitArray = test.split("-");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < splitArray.length; i++) {
stringBuffer.append(splitArray[i].charAt(0));
}
System.out.println(stringBuffer);
}
Using StringBuffer will save your memory as, if you use String a new object will get created every time you modify it.

Splitting and saving data in Java

I'm trying to read a data file and save the different variables into an array list.
The format of the data file looks a little like this like this
5003639MATH131410591
5003639CHEM434111644
5003639PSYC230110701
Working around the bad formatting of the data file, I added commas to the different sections to make a split work. The new text file created looks something like this
5,003639,MATH,1314,10591
5,003639,CHEM,4341,11644
5,003639,PSYC,2301,10701
After creating said file, I tried to save the information into an array list.
The following is the snippet of trying to do this.
FileReader reader3 = new FileReader("example.txt");
BufferedReader br3 = new BufferedReader(reader3);
while ((strLine = br3.readLine())!=null){
String[] splitOut = strLine.split(", ");
if (splitOut.length == 5)
list.add(new Class(splitOut[0], splitOut[1], splitOut[2], splitOut[3], splitOut[4]));
}
br3.close();
System.out.println(list.get(0));
The following is the structure it is trying to save into
public static class Class{
public final String recordCode;
public final String institutionCode;
public final String subject;
public final String courseNum;
public final String sectionNum;
public Class(String rc, String ic, String sub, String cn, String sn){
recordCode = rc;
institutionCode = ic;
subject = sub;
courseNum = cn;
sectionNum = sn;
}
}
At the end I wanted to print out one of the variables to see that it's working but it gives me an IndexOutOfBoundsException. I wanted to know if I'm maybe saving the info incorrectly, or am I perhaps trying to get it to print out incorrectly?
You have a space in your split delimiter specification, but no spaces in your data.
String[] splitOut = strLine.split(", "); // <-- notice the space?
This will result in a splitOut array of only length 1, not 5 like you expect.
Since you only add to the list when you see a length of 5, checking the list for the 0th element at the end will result in checking for the first element of an empty list, hence your exception.
If you expect your data to have a comma or a space separating the characters then you would alter the split line to be:
String[] splitOut = strLine.split("[, ]");
The split takes a regular expression as an argument.
Rather than artificially adding commas I would look at String.substring in order to cut the line you have read into pieces. For example:
while ((strLine = br3.readLine())!=null) {
if (strLine.length() != 20)
throw new BadLineException("line length is not valid");
list.add(new Class(strLine.substring(0,1), strLine.substring(1,7), strLine.substring(7,11), strLine.substring(11,15), strLine.substring(15,19)));
}
[ Untested: my numbers might be out because I a bit knacked, but you get the idea ]

Java Using a stack to reverse the words in a sentence [duplicate]

This question already has answers here:
Reversing characters in each word in a sentence - Stack Implementation
(6 answers)
Closed 9 years ago.
I am supposed to write a code that reads a sentence from the user and prints the characters of the words in the sentence backwards. It should include a helper method that takes a String as a parameter and returns a new String with the characters reversed. The individual words are reversed, for example the sentence "Hi dog cat". would print "iH god tac". I can make the entire sentence reverse but i cant figure out how to reverse individual words. Thanks! Also, i know how to return the String once i have found it, but i just cant get the right string
import java.util.Scanner;
import java.util.Stack;
public class ReverseStack
{
public static void main(String[] args)
{
String sentence;
System.out.println("Enter a sentence: ");
Scanner scan = new Scanner(System.in);
sentence = scan.nextLine();
String k = PrintStack(sentence);
}
private static String PrintStack(String sentence)
{
String reverse;
String stringReversed = "";
Stack<String> stack= new Stack<String>();
sentence.split(" ");
for(int i=0;i<sentence.length(); i++)
{
stack.push(sentence.substring(i, i+1));
}
while(!stack.isEmpty())
{
stringReversed += stack.pop();
}
System.out.println("Reverse is: " + stringReversed);
return reverse;
}
}
I will type an expatiation so you can still get the experience of writing the code, rather than me just giving you the code.
First create a Stack of Characters. Then use add each character in the String to the Stack, starting with the first char, then the second, and so on. Now either clear the String or create a new String to store the reversed word. Finally, add each character from the Stack to the String. This will pull the last character off first, then the second to last, and so on.
Note: I believe you have to use the Character wrapper class, rather than the primitive char; I may be incorrect about that though.
If you aren't familiar with how Stacks work, here is a nice interactive tool to visualize it: http://www.cise.ufl.edu/~sahni/dsaaj/JavaVersions/Stacks/AbstractStack/AbstractStack.htm
Change:
Stack<String> stack = new Stack<String>();
to be
Stack<Character> stack = new Stack<Character>();
and refactor your methods code as necessary; i.e.
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
I did it with a different kind of stack, but I suspect this might help
private static String reverseWord(String in) {
if (in.length() < 2) {
return in;
}
return reverseWord(in.substring(1)) + in.substring(0, 1);
}
private static String reverseSentence(String in) {
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(in);
while (st.hasMoreTokens()) {
if (sb.length() > 0)
sb.append(' ');
sb.append(reverseWord(st.nextToken()));
}
return sb.toString();
}
public static void main(String[] args) {
String sentence = "Hi dog cat";
String expectedOutput = "iH god tac";
System.out.println(expectedOutput
.equals(reverseSentence(sentence)));
}
Outputs
true

How can i use substring or other function to divide a string into words?

So I have this function:
public void actionPerformed(ActionEvent e)
{
String input = jt.toString();
}
And I want to use substring or any other function to divide the words in this sentence.
Like using substring from 0 until it finds a "space" and then it should stop and then start again until the end of the sentence.
What you need is to use the Split method for the String class.
String[] input = jt.toString().split("\\s+");
This method will give you an array where each cell of the array will contain a word.
jt stands for JText?
If yes, you should get the text from the component instead of converting the object to string using the following instruction: jt.getText()
string[] words = input.Split(' ')
You can also do it with stringbuilder if you care about saving memory.
public class splitword {
public static void main(String[] args) {
String input = "Hi! Can you please split me into pieces :0";
String[] toSplit = new StringBuilder(input).toString().split("[\\s\\p{P}&& [^']]+");
for (String x : toSplit) {
System.out.println(x);
}
}
}

Extract a substring up to 1000th comma

I have a string (comma seperated)
For example:
a,bgf,sad,asd,rfw,fd,se,sdf,sdf,...
What I need is to extract a substring up to the 1000th comma.
How to achieve this in Java?
An efficient way of doing this would be to use indexof(int ch, int fromIndex) intead of using split(String regex, int limit) or split(String regex) especially if the given string is long.
This could be done something like this
[pseudocode]
asciiCodeForComma = 0x2c
nextIndex=0
loop 1000 times
nextIndex= csv.indexof(asciiCodeForComma , nextIndex)
requiredSubString = csv.subString(0, nextIndex)
String csv = "some,large,string";
String[] parts = csv.split(",");
String thousandthElement = null; // the default value if there are less than 1000
if (parts.length > 999)
thousandthElement = parts[999];
You can use StringTokenizer with comma as separator, then loop nextToken() 1000 times.
I think he is asking for all 1000 element.. This should solve your problem. Understand and then copy-paste as this is ur homework :)
public static void main(String[] args) {
// TODO Auto-generated method stub
String samplecsv = "a,bgf,sad,asd,rfw,fd,se,sdf,sdf,";
String[] splitedText = samplecsv.split(",");
StringBuffer newtext = new StringBuffer();
for (int i = 0; i < 3; i++) {
newtext.append(splitedText[i]);
}
System.out.println(newtext);
}
So to solve this problem what you need to do is understand how to extract a string from a delimiter separated input stream. Then executing this for the case for N strings is trivial. The pseudocode for doing this for the individual record is below:
function parse(inputValue, delimiter)
{
return inputValue.split(delimiter)
}
Now to do that for the case where there are N inputValues is equally as trivial.
function parse(inputValues, delimiter)
{
foreach inputValue in inputValues
returnValue.append(parse(inputValue,delimiter)
return returnValue
}
There is actually built in functionality to do this by putting a second argument into split. If what you're really looking for is the whole string before the 1000th comma, you can still use this function but you will have to concatenate the first section of the array.
public static void main(String[] args){
String sample = "s,a,m,p,l,e";
String[] splitSample = sample.split(",",1000);
if (splitSample.length == 1000)
System.out.println(splitSample[1000]);
else
System.out.println("Your error string");
}

Categories

Resources