Trying to convert a text to a java string array - java

I'm trying to have an EditText that will check every word written while ignoring all special characters, and and add it to a String array. My idea was to make every new word clickable and use it to connect to an API.
I've tried a few things a found on the internet but never really worked.
#Override
public void afterTextChanged(Editable s) {
String string = editText_Main.getText().toString();
String[] arr = string.split(" ");
for ( String ss : arr) {
System.out.println("Adding: " + ss + " to words array");
words.add(ss);
}
System.out.println("Words array -> "+words);
}
So the idea was just to use the words array for creating all of the links and somehow using it to also link them to the EditText, but maybe this is a completely wrong approach and someone can lead me on a better path.

Instead of using
String string = editText_Main.getText().toString();
you should use
String string = s.getText().toString();

Related

Check exact word in scrabble words list

I have a Scrabble Clock with a verification tool inside.
The verification word space looks in green or red if the word that I check is in the list.
The thing is, if I use sbuffer.toString().contains, and write a word like ABA, the word space looks in green though ABA is not in the list, but ABAC, ABACA are in the list.
I would like to know how I can implement a condition in my code to check the exact complete word.
I've researched regex, boundary and matches, but I couldn't find a line code that words in my code.
Here is my code until now.
public class MainActivity extends AppCompatActivity {
TextView textView;
TextView textInV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.texto_1);
textView.setMovementMethod(new ScrollingMovementMethod());
textInV = findViewById(R.id.textIn);
String data = "";
StringBuffer sbuffer = new StringBuffer();
InputStream is = this.getResources().openRawResource(R.raw.fruits);
BufferedReader reader = new BufferedReader((new InputStreamReader(is)));
if (is != null)
{
try
{
while((data =reader.readLine())!=null)
{
sbuffer.append((data + "\n"));
}
is.close();
}
catch (Exception e){ e.printStackTrace();}
}
textView.setText(sbuffer);
}
}
The contains method on a string tests whether the target is contained as a substring; if ABAC is contained as a substring then so is ABA, since ABA is a substring of ABAC and hence it is also a substring of any string which ABAC is a substring of. Therefore, it is not logically possible for the String.contains method to return true for ABAC and false for ABA.
You want to test if the target is one of the elements of a collection of strings, so you should use contains on a collection of strings, not on a string. The best choice is a HashSet, since this performs membership tests in O(1) time on average.
> import java.util.*;
> Set<String> allowed = new HashSet<>();
> allowed.add("ABAC");
> allowed.add("ABACA");
> allowed.contains("ABA")
false
> allowed.contains("ABAC")
true
As #Ashutosh KS has already mentioned, String.contains is not really what you are looking for in this case: You want to check if two strings are identical, not if one contains the other.
The Java String class contains a few methods that you can use to compare the content of two strings, of which you can choose accordingly to match your exact use case:
contentEquals(CharSequence cs) and contentEquals(StringBuffer sb) both check if the passed string representation's content matches the current one.
equals(Object str) is similar to contentEquals in that it makes an exact comparison between both strings, however it also checks to make sure that the passed object is in fact a string.
equalsIgnoreCase(String anotherString), as the name implies, will do a check while ignoring the string case.
These are the 'proper' ways to compare two strings exposed by the native API, so while it is absolutely possible to use other methods, it is a good idea to stick to these.
StringBuffer's contains() check if the given string is a substring of the text in the sbuffer. That means, it will output true for searching "ABC" in "ABC", "ABCBC", "ZABC", "ZABCBC"...
If you want to search for a complete word in the sbuffer, then you can look for "\n" + "ABC" + "\n" since you're adding "\n" when adding words to sbuffer: sbuffer.append((data + "\n"));. But, you must also initialize sbuffer with "\n": StringBuffer sbuffer = new StringBuffer("\n");.
sbuffer.toString().contains("\n" + "ABC" + "\n"); // this will do the trick
Test code:
class Main {
public static void main(String[] args) {
StringBuffer sbuffer = new StringBuffer("\n");
StringBuffer sbuffer2 = new StringBuffer("\n");
sbuffer.append("ABC" + "\n");
sbuffer.append("ABCBC" + "\n");
sbuffer.append("ZABC" + "\n");
sbuffer.append("ZABCBC" + "\n");
System.out.println("Is ABC in sbuffer = " + sbuffer.toString().contains("\n" + "ABC" + "\n"));
sbuffer2.append("ABCBC" + "\n");
sbuffer2.append("ZABC" + "\n");
sbuffer2.append("ZABCBC" + "\n");
System.out.println("Is ABC in sbuffer2 = " + sbuffer2.toString().contains("\n" + "ABC" + "\n"));
}
}
Test output:
Is ABC in sbuffer = true
Is ABC in sbuffer2 = false
Now i have this, and works, but i have a file with the words, and i would like to add the files in the diccionario.
But i don't know how to read the file. I have try bufferread, but i need try/catch, and not works....
Some other solutions....
Thanks
boton2.setOnClickListener(new View.OnClickListener()
{
String content;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View view)
{
HashSet<String> diccionario = new HashSet<String>();
//Adding elements to HashSet
diccionario.add("CASA");
diccionario.add("ABAC");
if(diccionario.contains(textIn.getText().toString().toUpperCase()))
{
textIn.setBackgroundColor(Color.GREEN);
}
else
{
textIn.setBackgroundColor(Color.RED);
}
}

My Question Is input : String s=" learning java programming by self" and output is : "gninrael java gnimmargopr by fles ? plese help"

The String contains Group of words.Write a program to print even words in reverse and odd words as same in the given sentence.
i tried with split(" ") but i am not getting to reverse the even words
input is : "am learning java with stackoverflow"
output : "ma learning avaj with wolfrevokcats"
Code:
class StringJumbling {
public static void main(String args[]) {
String s="my name is baghyavathi";
String arr[]=s.split(" ");
String reverse="";
int sr=arr.length;
for(int srk=0;srk>=sr-1;srk++) {
if(sr % 2 == 0) {
reverse = reverse + " " + arr[sr];
}
}
System.out.println(reverse);
}
}
Just a guidance.
Create a function that can reverse any string. This could be approached by converting string to char array and then you've to loop in reverse order.
For selecting even and odd words, again you tokenize using split and then you can select even and odd based on index.
Now, you can target one point at a time to solve this problem.
I hope this helps. That's how you learn the hard way.
Find a way to convert string to char array and that's the only difficult part I believe for you based on your question. Good luck.

How to make spaced text .equal() to unspaced text

I am working on code that takes two inputs like the following:
,Air Condition,
, Air Condition,
This text is received from a JSON object and the commas are something that must be considered.
As can be seen, one has white space at the beginning and the other doesn't. How can I compare them using the equals()?
So far, I have used the following code to compare the two strings:
if (oldSelected.get(i).equalsIgnoreCase(String.valueOf(fc.getText()))){
fc.setChecked(true);
}
However, it doesn't do what I expect it to do.
How i can trim this space and get the desired results?
You need to trim the white spaces first.
String oldSelected = ",Air Conditioner,";
String newSelected = ", Air Conditioner, ";
if(oldSelected.replaceAll("\\s", "").equalsIgnoreCase(newSelected.replaceAll("\\s", ""))){
// Do Something
}
else{ // Do Something Else
}
Hope that helps! :)
You can do something like this:
public static void main(String[] args) {
String s1 = ",Air Condition";
String s2 = ", Air Condition";
System.out.println(s1.equals(s2.replace(", ", ",")));
}
or, if you want to keep space between words, you may use like this:
public static void main(String[] args) {
String s1 = ",Air Condition";
String s2 = ", Air Condition";
System.out.println(s2.split(", ")[1]);
System.out.println(s1.split(",")[1]);
System.out.println(s1.split(",")[1].equals(s2.split(", ")[1]));
}
Try,
String.valueOf(fc.getText())).replaceAll("\\s+","")
This removes all whitespaces and non-visible characters (e.g. tab, \n)
you can use String methot called SPLIT for example you have
String STR1 = "Ahoj"
String STR2 = "Ahoj "
String x[] = STR1.split(" ");
String y[] = STR2.split(" ");
then use simple for loop to check all words :)
Well, worked solution as #Rahul suggest to use .trim() but this worked with english words only, so in order to equalize all language i trim the equalized text to as below :
String checkedVal = oldSelected.get(i);
checkedVal = checkedVal.trim();
if (checkedVal.equalsIgnoreCase(String.valueOf(fc.getText().toString().trim()))){
fc.setChecked(true);
}
Thanks for all answers.

How to split a string that the user enters

Ok so I have looked at this (question asking how to split a string) however the answer isn't really relevant to my question.
The user will input a weight which is stored in the sqlite DB but I also want the number to show in a TextView below where it was just entered (as the app keeps track of weights over a period of 7 days).
When I try and get the String from my DB its stored as a long String and what I want to do is split that String (I hope I'm making sense!).
I have the following method;
public String[] getWeight() {
String selectQuery = "SELECT " + DowncroftContract.WEIGHT_VALUE + " FROM " + DowncroftDatabase.WEIGHT_TABLE; //+ " WHERE " + DowncroftContract.WEIGHT_DOGS_ID + " = " + str_dogsId + " ORDER BY " + DowncroftContract.WEIGHT_DATE + " ASC;";
SQLiteDatabase db = downcroftDatabase.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
if (cursor.moveToFirst()) {
do {
results = cursor.getString(cursor.getColumnIndex(DowncroftContract.WEIGHT_VALUE + ""));
String[] splitString = results.split("");
String split1 = splitString[1];
String split2 = splitString[2];
DayOne.append(split1);
DayTwo.append(split2);
} while (cursor.moveToNext());
}
cursor.close();
return data;
}
Now the above method will split the string up to single figures but I cant seem to figure out how to split the string so that its splitting it for every two figures.
E.G User enters 20 presses enter - it then drops down into a TextView called DayOne.
The following day the users enters 24 and presses enter- that then drops down into a TextView called DayTwo.
I think I need an array with possibly a for loop however I am wondering if it is possible to achieve what I want by tweaking what I already have?
You just mean you want to split a String every 2 characters?
Like you have string 123456 and you want 12, 34, 56?
Try this:
String[] split = result.split("(?<=\\G..)");
This is gonna split your String every 2 characters. \G asserts the position after previous match (or the start of the String if there's not previous match) followed by 2 characters.
[Guy above did basically the same thing, only saw on refresh, snippet will probably still be useful though..]
The part that is splitting your string is String[] splitString = results.split("");
This splits after every "nothing", so in essence, after every character split the string.
Here's a little code snippet I worked together for you...
import java.util.Arrays; //only essential for the Arrays toString bit...
public class Main {
//Static so it's usable anywhere..
public static String[] splitStringBy(int everyXLetter, String stringCode)
{
// Split the given string by regex, every Xth letter...
String[] splitIntoSingleElements = stringCode.split("(?<=\\G.{"+everyXLetter+"})");
// Return it
return splitIntoSingleElements;
}
public static void main(String[] args)
{
//Set some string text...
String text = "askfjaskfjasf";
//Split and store the string using the above function
String[] splitText = splitStringBy(2, text);
//Return it any way you like
System.out.println(Arrays.toString(splitText)); // [as, kf, ja, sk, fj, as, f]
System.out.println(splitText[0]); // as
}
}

Splitting String according to multiple String in java

I just beginning to learn java, so please don't mind.
I have string
String test="John Software_Engineer Kartika QA Xing Project_Manager Mark CEO Celina Assistant_Developer";
I want to splitting based of position of Company={"Software_Engineer", "QA","Project_Manager","CEO ","Assistant_Developer"};
EDITED:
if above is difficulties then is it possible??? Based or {AND, OR)
String value="NA_USA >= 15 AND NA_USA=< 30 OR NA_USA!=80"
String value1="EUROPE_SPAIN >= 5 OR EUROPE_SPAIN < = 30 "
How to split and put in hashtable in java. finally how to access it from the end. this is not necessary but my main concern is how to split.
Next EDIT:
I got solution from this, it is the best idea or not????
String to="USA AND JAPAN OR SPAIN AND CHINA";
String [] ind= new String[]{"AND", "OR"};
for (int hj = 0; hj < ind.length; hj++){
to=to.replaceAll(ind[hj].toString(), "*");
}
System.out.println(" (=to=) "+to);
String[] partsparts = to.split("\\*");
for (int hj1 = 0; hj1 < partsparts.length; hj1++){
System.out.println(" (=partsparts=) "+partsparts[hj1].toString());
}
and
List<String> test1=split(to, '*', 1);
System.out.println("-str333->"+test1);
New EDIT:
If I have this type of String how can you splitting:
final String PLAYER = "IF John END IF Football(soccer) END IF Abdul-Jabbar tennis player END IF Karim -1996 * 1974 END IF";
How can i get like this: String [] data=[John , Football(soccer) ,Abdul-Jabbar tennis player, Karim -1996 * 1974 ]
Do you have any idea???
This will split your string for you and store it in a string array(Max size 50).
private static String[]split = new String[50];
public static void main(String[] args) {
String test="John -Software_Engineer Kartika -QA Xing -Project_Manager Mark -CEO Celina -Assistant_Developer";
for (String retval: test.split("-")){
int i = 0;
split[i]=retval;
System.out.println(split[i]);
i++;
}
}
You can make a string with Name:post and space. then it will be easy get desire value.
String test="John:Software_Engineer Kartika:QA Xing:Project_Manager"
I am unable to comment as my reputation is less. Hence i am writing over here.
Your first Question of String splitting could be generalized as positional word splitting. If it is guaranteed that you require all even positioned string, you could first split the string based on the space and pull all the even position string.
On your Second Question on AND & OR split, you could replace all " AND " & " OR " with single String " " and you could split the output string by single space string " ".
On your third Question, replace "IF " & " END" with single space string " " and I am not sure whether last IF do occurs in your string. If so you could replace it too with empty string "" and then split the string based on single space string " ".
First classify your input string based on patterns and please devise an algorithm before you work on Java.
I would suggest you to use StringBuffer or StringBuilder instead of using String directly as the cost is high for String Operation when compared to the above to.
try this
String[] a = test.replaceAll("\\w+ (\\w+)", "$1").split(" ");
here we first replace word pairs with the second word, then split by space
You can take a set which have all positions Like
Set<String> positions = new HashSet<String>();
positions.add("Software_Engineer");
positions.add("QA");
String test="John Software_Engineer Kartika QA Xing Project_Manager Mark CEO Celina Assistant_Developer";
List<String> positionsInString = new ArrayList<String>();
Iterator<String> iterator = positions.iterator();
while (iterator.hasNext()) {
String position = (String) iterator.next();
if(test.contains(position)){
positionsInString.add(position);
break;
}
}

Categories