I have a task which involves me creating a program that reads text from a text file, and from that produces a word count, and lists the occurrence of each word used in the file. I managed to remove punctuation from the word count but I'm really stumped on this:
I want java to see this string "hello-funny-world" as 3 separate strings and store them in my array list, this is what I have so far , with this section of code I having issues , I just get "hello funny world" seen as one string:
while (reader.hasNext()){
String nextword2 = reader.next();
String nextWord3 = nextword2.replaceAll("[^a-zA-Z0-9'-]", "");
String nextWord = nextWord3.replace("-", " ");
int apcount = 0;
for (int i = 0; i < nextWord.length(); i++){
if (nextWord.charAt(i)== 39){
apcount++;
}
}
int i = nextWord.length() - apcount;
if (wordlist.contains(nextWord)){
int index = wordlist.indexOf(nextWord);
count.set(index, count.get(index) + 1);
}
else{
wordlist.add(nextWord);
count.add(1);
if (i / 2 * 2 == i){
wordlisteven.add(nextWord);
}
else{
wordlistodd.add(nextWord);
}
}
This can work for you ....
List<String> items = Arrays.asList("hello-funny-world".split("-"));
By considering that you are using the separator as '-'
I would suggest you to use simple split() of java
String name="this-is-string";
String arr[]=name.split("-");
System.out.println("Here " +arr.length);
Also you will be able to iterate through this array using for() loop
Hope this helps.
I want to return words from a String array one after the other.
public String CurrentString(int move) {
int currentString = 0;
EditText ed = (EditText) findViewById(R.id.ed);
String[] strings = ed.getText().toString().split(" ");
int newString = currentString move;
if (newString >= strings.length) {
// if the new position is past the end of the array, go back to the beginning
newString = 0;
}
if (newString < 0) {
// if the new position is before the beginning, loop to the end
newString = strings.length - 1;
}
currentString = newString;
Toast.makeText(getApplicationContext(), strings[currentString],Toast.LENGTH_LONG).show();
return strings[currentString];
}
The problem is that my above code doesn't return all texts. Please, help.
Seems you have not done enough "homework" and are having problems with arrays, (that's why people are down-voting [this is not a site for beginners who not do put in the required "research effort", the site would be inundated]).
The current trend is to downvote AND/OR leave a sarcastic comment ;O)
Also your code contains errors that will not compile, so you have not even bothered to test it ! ;O(
Lucky for you you cannot get a negative reputation !
Seriously please do some research (google it !)
Here is some code that may help. Use split to process your string into a string array:
String string = "I want a string array of all these words";//input string
// ^ ^ ^ ^ ^ ^ ^ ^ ^
// 0 1 2 3 4 5 6 7 8 //index
String[] array_of_words;//output array of words
array_of_words = CurrentString(string);//execute method
Log.i("testing", array_of_words[8]);//this would be "words" in this example
//later you might want to process commas and full stops etc...
public String[] CurrentString(String string)
{
String[] array = string.split(" "); //use space to split string into words
//With the advent of Java 5, we can make our for loops a little cleaner and easier to read
for ( String sarray : array ) //loop through String array
{
Log.i("CurrentString", sarray );//print the words
}
return array ;//return String array
}
So i'm trying to reverse a sentence and even though I don't have any errors when compiling, it tells me my reverse sentence is out of bounds.
-It should work like this: "hello, world!" --> !dlrow ,olleh"
Said code:
String sentence="this is a sentence!";
String reverseSentence=sentence;
for(int counter=0;counter<sentence.length();counter++)
{
char charToReplace,replaceChar;
charToReplace = reverseSentence.charAt(counter);
replaceChar = sentence.charAt(sentence.length()-counter);
reverseSentence=reverseSentence.replace(charToReplace, replaceChar);
System.out.println(reverseSentence);
}
The reason for the exception you are getting is that in sentence.charAt(sentence.length()-counter), sentence.length()-counter is out of bounds when counter is 0. Should be sentence.length()-1-counter.
However, as Tunaki commented, there are other problems with your code. I suggest you use a StringBuilder to construct the reversed String, instead of using replace (which would replace any occurrence of the first character with the second character).
You can use character arrays to implement your requirement like this,
String sentence = "ABDEF";
char[] firstString = sentence.toCharArray();
char[] reversedString = new char[sentence.length()];
for (int counter = 0; counter < sentence.length(); counter++) {
reversedString[counter] = firstString[sentence.length() - counter -1];
}
System.out.println(String.copyValueOf(reversedString));
It doesn't show you an error because the Exception concerning the indexes happen at RunTime.
Here :
replaceChar = sentence.charAt(sentence.length()-counter);
You're trying to access index 19 of your String (19-0). Replace it with :
replaceChar = sentence.charAt(sentence.length()-counter-1);
I'd recommend to use a StringBuilder in your situation though.
Either use the reverse() method :
String sentence = "this is a sentence!";
String reversed = new StringBuilder(sentence).reverse().toString();
System.out.println(reversed); // Prints : !ecnetnes a si siht
Or use the append() method for building your new String object. This uses less memory than using a String because it is not creating a new String object each time you're looping :
String sentence = "this is a sentence!";
StringBuilder reversed = new StringBuilder();
for (int i = 0 ; i < sentence.length() ; i++){
reversed.append(sentence.charAt(sentence.length() - 1 - i));
}
System.out.println(reversed.toString()); // Prints : !ecnetnes a si siht
It maybe better to do it without any replacement, or for loop. It you create a char array from the string, reverse the array, then create a string from the reversed array this would do what you've asked without any moving parts or replacements. For example:
String hw = "hello world";
char[] hwChars = hw.toCharArray();
ArrayUtils.reverse(hwChars);
String wh = new String(hwChars);
System.out.println(wh);
Just split the String at each whitespace and put it in String array and then print the array in reverse order
public static void main(String[] args) {
String sentence = "this is a sentence!";
String[] reverseSentence = sentence.split(" ");
for (int i = reverseSentence.length-1; i >= 0; i--) {
System.out.print(" " + reverseSentence[i]);
}
}
I have a String[] and an input String:
String[] ArrayEx = new String[1];
String textInput = "a whole bunch of words"
What I want to do is check if the String contains a word present in the Array, like this.
Ex: textInput = "for example" and ArrayEx[0] = "example"
I know about this method:
Arrays.asList(yourArray).contains(yourValue)
but it checks the full String right? How do I check if the String contains a particular word present in the Array. Even if it is from an ArrayList I have no problem.
Also if yes, can I get that word from the String[]? i.e., in the above case get the String "example".
EDIT:
public void searchNearestPlace(String v2txt)
{
Log.e("TAG", "Started");
v2txt = v2txt.toLowerCase();
String[] places = {"accounting, airport, amusement_park, aquarium, art_gallery, atm, bakery, bank, bar, beauty_salon, bicycle_store, book_store, bowling_alley, bus_station, cafe, campground, car_dealer, car_rental, car_repair, car_wash, casino, cemetery, church, city_hall, clothing_store, convenience_store, courthouse, dentist, department_store, doctor, electrician, electronics_store, embassy, establishment, finance, fire_station, florist, food, funeral_home, furniture_store, gas_station, general_contractor, grocery_or_supermarket, gym, hair_care, hardware_store, health, hindu_temple, home_goods_store, hospital, insurance_agency, jewelry_store, laundry, lawyer, library, liquor_store, local_government_office, locksmith, lodging, meal_delivery, meal_takeaway, mosque, movie_rental, movie_theater, moving_company, museum, night_club, painter, park, parking, pet_store, pharmacy, physiotherapist, place_of_worship, plumber, police, post_office, real_estate_agency, restaurant, roofing_contractor, rv_park, school, shoe_store, shopping_mall, spa, stadium, storage, store, subway_station, synagogue, taxi_stand, train_station, travel_agency, university, veterinary_care, zoo"};
int index;
for(int i = 0; i<= places.length - 1; i++)
{
Log.e("TAG","for");
if(v2txt.contains(places[i]))
{
Log.e("TAG", "sensed?!");
index = i;
}
}
Say v2txt was "awesome airport" the sensed Log never does appear even though all other logs indicate it working
Edit2:
I am so embarrassed that I made such a dunder head mistake. My array is declared wrongly. There should be a " before every ,. I am such a big idiot!
Sorry will change it and let you know.
First of all it has nothing to do with android
Second the solution
boolean flag = false;
String textInput = "for example";
int index = 0;
String[] yourArray = {"ak", "example"};
for (int i = 0; i <= yourArray.length - 1; i++) {
if (textInput.contains(yourArray[i])) {
flag = true;
index = i;
}
}
if (flag)
System.out.println("found at index " + index);
else
System.out.println("not found ");
DEMO
EDIT :
Change your array to
String[] places = {"accounting", "airport", "amusement_park" };
and so on with other values with your array declaration it has one index.
you can split your string and get array of words
txArray = textInput.split(" ");
then for each element in txArray check if
Arrays.asList(ArrayEx).contains(txArray[i])
txArray = "Hello I'm your String";
String[] splitStr = txArray.split(" ");
int i=0;
while(splitStr[i]){
if(Arrays.asList(ArrayEx).contains(txArray[i])){
System.out.println("FOUND");
}
i++;
}
You can use Java - Regular Expressions.
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Testing {
public static void main(String[] args) {
String textInput = "for example";
String[] arrayEx = new String[1];
arrayEx[0] = "example";
Pattern p = Pattern.compile(arrayEx[0]);
Matcher m = p.matcher(textInput);
boolean matchedFoundStatus = false;
while (m.find()) {
matchedFoundStatus = true;
}
System.out.println("matchedFoundStatus:" + matchedFoundStatus);
}
}
Try this;
Sting text2check = "Your Name":
for(int t = 0; t < array.length; t++)
{
if (text2check.equals(array[t])
// Process it Here
break;
}
"How do I check if the String contains a particular word present in the Array?" is the same thing as Is there an element in the array, for which the input string contains this element
Java 8
String[] words = { "example", "hello world" };
String input = "a whole bunch of words";
Arrays.stream(words).anyMatch(input::contains);
(The matching words can also be extracted, if needed:)
Arrays.stream(words)
.filter(input::contains)
.toArray();
If you are stuck with Java 7, you will have to re-implement "anyMatch" and "filter" yourself:
Java 7
boolean anyMatch(String[] words, String input) {
for(String s : words)
if(input.contains(s))
return true;
return false;
}
List<String> filter(String[] words, String input) {
List<String> matches = new ArrayList<>();
for(String s : words)
if(input.contains(s))
matches.add(s);
return matches;
}
This will take an String array, and search through all the strings looking for a specific char sequence found in a string. Also, native Android apps are programmed in the Java language. You might find it beneficial to read up more on Strings.
String [] stringArray = new String[5];
//populate your array
String inputText = "abc";
for(int i = 0; i < stringArray.length; i++){
if(inputText.contains(stringArray[i]){
//Do something
}
}
Well I'm almost finished with my world editor thanks to this great community, the only thing I need to know is how I can tell my read File code to process specific letters. When I hit enter on my keyboard I will write coordinates of a Vector3f to a text file, this Vector3f is the posistion of my active GameObject. My ProcessText method can read a text file and process the coordinates however he can only read ony type of format:
public void ProcessText()
{
String file_name = "C:/Users/Server/Desktop/textText.txt";
try
{
ProcessCoords file = new ProcessCoords(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
if(aryLines[i].startsWith("makeGrass:")) {
String Arguments = aryLines[i].substring(aryLines[i].indexOf(":")+1, aryLines[i].length());
String[] ArgArray = Arguments.split(",");
this.makeGrass(Double.parseDouble(ArgArray[0]),
Double.parseDouble(ArgArray[1]),
Double.parseDouble(ArgArray[2]));
}
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
In the above example my ProcessText method can only process the coordinates if they are written like this:
makeGrass:x,y,z //for example makeGrass:5,1,9
But when I press enter and write the coordinates from what me my engine gives I'm getting a different format:
makeGrass:(x y z) //for example makeGrass:(3 1 4)
Now what I need to know is how I have to rewrite the code in my ProcessText method so it accounts for the other format that has brackets at the beginning and end and also with spaces to sepearta x from y and y from z instead of commas.
I really don't knwo where else I would find an answer to this question so I'd apreciate any help and explanation as to how this works.
Thanks a lot in advance!
You want to accept as many formats as possible?
Instead of splitting I would try to match, this is safer and doesn't need any pre- or post-processing of the input or the received substrings:
Pattern pattern = Pattern.compile("([0-9]+)"); // outside of method
long[] ArgArray = new long[3];
Matcher matcher = pattern.matcher(Arguments);
int i = 0;
while (matcher.find() && i < 3) {
ArgArray[i++] = Long.parseLong(matcher.group(1));
}
// there was a mistake if i < 3, otherwise you have 3 numbers in ArgArray
If you want to split, you could maybe try this: split("[^0-9]+")
To only match makeGrass:(x y z)
Pattern pattern = Pattern.compile("^makeGrass:\\(([0-9]+) ([0-9]+) ([0-9]+)\\)$");
Like this you can directly match the line and have the 3 numbers in groups 1 - 3 (as String) after calling find once, if (matcher.find()) will decide if it's a valid makeGrass line and if so it can be processed in the if.
if you can guarantee that there will not be any spaces in the makeGrass:x,y,z format and that there will not be any parenthesis in it either then you can use String.replaceAll()... Something like below:
myString = "makeGrass:(3 1 4)"
myString = myString.replaceAll("\(", ""); //replace ( with empty space
myString = myString.replaceAll("\)", ""); //replace ) with empty space
myString = myString.replaceAll(" ", ","); //replace spaces with commas
then you don't need to different methods to handle the two types of input. just format as shown above and pass both inputs to the same method
Going this way you will not need to split on certain chars and then rebuild the string to fit your format
Just split with the regular expression : [\s,]
Splits the String at places where there is either a white space or a ,.
And use this to get rid of any brackets if present :
Arguments = Arguments.replaceAll("\\(", "").replaceAll("\\)", "");
( and ) are part of regex notation. So, they need to be escaped with \ and \ being a Java notation, needs to be escaped with another\. Hence it becomes `"\(". And we have to replace the string and store it back to the String variable. Because Java is pass by value. Both the operations are done in the same line.
The modified code for the method is :
public void ProcessText() {
String file_name = "C:/Users/Server/Desktop/textText.txt";
public void ProcessText()
{
String file_name = "C:/Users/Server/Desktop/textText.txt";
try
{
ProcessCoords file = new ProcessCoords(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
if(aryLines[i].startsWith("makeGrass:")) {
String Arguments = aryLines[i].substring(aryLines[i].indexOf(":")+1, aryLines[i].length());
Arguments = Arguments.replaceAll("\\(", "").replaceAll("\\)", "");
String[] ArgArray = Arguments.split("[\\s,]");
this.makeGrass(Double.parseDouble(ArgArray[0]),
Double.parseDouble(ArgArray[1]),
Double.parseDouble(ArgArray[2]));
}
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
}