I'm trying to write a method that will take a sentence (a String) and convert it into an array of words (Strings) (and it will return this array). I'm looking for a manual way to do this, without .split or tokenize.
So far, all I have in terms of code is the name of my method
public String[] tokenize();
After that, I'm at a loss of where to start. Any help is appreciated, thanks.
EDIT: The string is not of fixed length, the input sentence can be anything.
You probably would want to use java.util.Scanner and construct the scanner with the string
Scanner sc = new Scanner(string);
sc.useDelimiter(\p{Space});
while(sc.hasNext)
{
string[i] = sc.next();
}
or something like that
Or, use a for loop, check each character, and chop off a substring.
Related
We were told to do a program on stings and I wasn't able to attend class because I was sick. I am asking for your help on this task that was given to us.
Create a java program that will ask the user to input two Strings. Compare the two strings and display the letters that are found on the first string but are not found on the second string.
Here is what I have at the moment https://pastebin.com/7a4dHecR
I really have no Idea what to do so any help would be appreciated!
https://pastebin.com/7a4dHecR
import java.util.*;
public class filename{
public static void main(String[] args){
Scanner sc =new Scanner(System.in);
System.out.print("Input first string: ");
String one=sc.next();
System.out.println();
System.out.print("Input second string: ");
String two=sc.next();
}
}
There are many ways to do this. I'm going to give you some parts you can put together. They are not the shortest or simplest way to solve this particular problem, but they will be useful for other small programs you write.
Here are some hints:
First, figure out how to step through your code with a debugger.
Second, figure out how to find the Javadoc for Java library classes and their methods.
You need to do something for each character in a string. Use a for loop for that:
for (int i = 0; i < one.length(); i++) {
// your code here
}
You need to get a particular character of a String.
String c = one.substring(i, i+1);
Read the Javadoc for String.substring to understand what the i and i+1 parameters do.
Now you need to find a way to check whether a String contains another String. Look at the Javadoc for the String class.
Then you can put all this together.
You could try the following:
String diff: StringUtils.difference(one, two);
System.out.println(diff);
I have a very specific problem for my CS course. I have a sentence in a string, and I need that separated into individual words within an ArrayList, and cannot use the split method.
The issue I have is that I have had zero teaching on arrays, only the bare minimum teaching for loops and String statements. I've done a lot of research and figured out the best way to go about making the loop, and sending the words to the ArrayList, however I still can't find a good way to actually have it loop through the sentence and separate each individual word at all. I get how easily it can be done to separate the very first word, however after that I get lost. I have no idea how to make the loop for its other iterations specifically grab the next word in the sentence after the one it previously got.
(Note: The only utilities imported are Scanner, File, HashMap, ArrayList, Random, and *)
What I'm looking for is any tips of specific methods I should try and employ or research. Or perhaps a set of code that is fairly functional in doing something similar to what I'm looking for that I can look at and build my own code off of.
When you said the word "word"(That's weird) I assume that they are separated by spaces. If you are reading in the inputs, then just use Scanner... Then:
Scanner input = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
for(int i = 0;i<numberOfWord;i++){
words.add(input.next());// .next() method read data that are separated by space
}
or:
String theLineOfWord;//Given to you
StringTokenizer st = new StringTokenizer(theLinOfWord);//Used to separate words.
ArrayList<String> words = new ArrayList<String>();
while(st.hasMoreTokens()){
words.add(st.nextToken();
}
or:
public static ArrayList<String> getWords(String line){
ArrayList<String> words = new ArrayList<String>();
line += " ";//add a space to ignore the ending case
while(line.length() != 0) {
words.add(line.substring(0, line.indexOf(' ')));//add the word to the list
line = line.substring(line.indexOf(' ') + 1, line.length());//take out the useless string away
}
return words;
}
I have to write a program which prints the String which are inputed from a user and every letter like the first is replaced with "#":
mum -> #u#
dad -> #a#
Swiss -> #wi## //also if it is UpperCase
Albert -> Albert //no letter is like the first
The user can input how many strings he wants. I thought to split the strings with the Split method but it doesn't work with the ArrayList.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
ArrayList <String> Parolecens= new ArrayList <String>();
while (s.hasNextLine()) {
tdc=s.nextLine();
Parolecens.add(tdc);
}
System.out.println(Parolecens);
}
}
If you want to read in single words you can use Scanner.next() instead. It basically gives you every word, so every string without space and without newline. Also works if you put in two words at the same time.
I guess you want to do something like this. Feel free to use and change to your needs.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
while (s.hasNext()) {
tdc=s.next();
char c = tdc.charAt(0);
System.out.print(tdc.replaceAll(Character.toLowerCase(c) +"|"+ Character.toUpperCase(c), "#"));
}
}
}
Edit:
Basically it boils down to this. If you want to read single words with the scanner use .next() instead of .nextLine() it does consider every word seperated by space and newline, even if you put in an entire Line at once.
Tasks calling for replacing characters in a string are often solved with the help of regular expressions in Java. In addition to using regex explicitly through the Pattern class, Java provides a convenience API for using regex capabilities directly on the String class through replaceAll method.
One approach to replacing all occurrences of a specific character with # in a case-insensitive manner is using replaceAll with a regex (?i)x, where x is the initial character of the string s that you are processing:
String result = s.replaceAll("(?i)"+s.charAt(0), "#");
You need to ensure that the string is non-empty before calling s.charAt(0).
Demo.
Assuming that you've successfully created the ArrayList, I'd prefer using the Iterator interface to access each elements in the ArrayList. Then you can use any String variable and assign it the values in ArrayList . Thereafter you can use the split() in the String variable you just created. Something like this:
//after your while loop
Iterator<String> it = Parolecens.iterator();
String myVariable = "";
String mySplitString[];
while(it.hasNext()) {
myVariable = it.next();
mySplitString = myVariable.split(//delimiter of your choice);
//rest of the code
}
I hope this helps :)
Suggestions are always appreciated.
I have a string that I want to read line by line:
"8688642986379252 Michael_Thompson 816 2500.0
8904000405634912 Barbara_Martin
8610835007621519 Charles_Jackson 1019 52800.0"
It goes on on and on in that format.
I tried separating it using for loops, charAt() and reducing the size of the string using substring() but I failed miserably.
I'm sure it's something simple but I just can't get it. Any ideas?
I would suggest using str.split("\n"). It will produce an array of strings, one index for each line. This is assuming you can read the whole thing into a string. If the input is large, this won't work.
Use Scanner to read line by line using nextLine. Then, split every String by blank space" ":
Scanner scanner = new Scanner(stringWithBreaklines);
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] content = line.split(" ");
//do what you want/need with content
}
If the String is inside a file, then read the file directly using Scanner:
Scanner scanner = new Scanner(new File("file.txt"));
//same code as above...
Use the java.util.Scanner class to read tokens one by one.
http://docs.oracle.com/javase/tutorial/essential/io/scanning.html
For my assignment I've had to create an ArrayStack, a StackADT, and now I have to make a program to take in a string and output it in reverse.
Now this sounds simple, but I have no idea how to push something into the array. I've been googling the shit out of this and can't find an actual answer that makes sense.
Specifically I'm having trouble linking the main program to the actual array, and then linking the input string to the push().
public class ReverseSentenceMain {
public static void main (String[] args)
{
AssignmentArrayStack stack = new AssignmentArrayStack();
//private AssignmentArrayStack<String> stack;
public ReverseSentenceMain()
{
stack = new AssignmentArrayStack<Integer>();
}
String sentence;
String result = null;
String words;
stack = (T[])(new Object[initialCapacity]);
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence");
}
}
I'd appreciate any help and thanks for your time
You start scanning by calling next on the scanner.
sentence = in.next();
Then you perform a split on whitespace to divide up the sentence into tokens that you push into your stack. The scanner can do the split for you I think. Look at the Scanner JavaDoc or String JavaDoc for more information.
You should format the code. Press ctrl+K or use the little 101010 icon.
Anyways. The stack class should have a push method. You need to get the sentence. You could loop through the sentence and then push the characters onto a stack. Once you do that, then you can pop the characters off to print the string in reverse order.
loop through string
stack.push(string[i])
while(currChar = stack.pop())
print currChar (or store to another variable)
I believe that will work. Been a while since ive done anything in java.
A stack isn't really an array. Its more like a linked list. It adds an element as the first element in a linked list and then updates the pointer.
Acutally heres a decent example http://www.javacoffeebreak.com/faq/faq0037.html
And i just noticed you want to reverse the sentence and not the word, so do what willcodejavaforfood said and tokenize it with scanner. I remember you can do this. It will read up every whitespace. you get that token and add it to the stack. Some kind of type of concept though.