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;
}
}
Related
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.
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
}
}
I try to write equals override function. I think I have written right but the problem is that parsing the expression. I have an array type of ArrayList<String> it takes inputs from keyboard than evaluate the result. I could compare with another ArrayList<String> variable but how can I compare the ArrayList<String> to String. For example,
String expr = "(5 + 3) * 12 / 3";
ArrayList<String> userInput = new ArrayList<>();
userInput.add("(");
userInput.add("5");
userInput.add(" ");
userInput.add("+");
userInput.add(" ");
userInput.add("3");
.
.
userInput.add("3");
userInput.add(")");
then convert userInput to String then compare using equals
As you see it is too long when a test is wanted to apply.
I have used to split but It splits combined numbers as well. like 12 to 1 and 2
public fooConstructor(String str)
{
// ArrayList<String> holdAllInputs; it is private member in class
holdAllInputs = new ArrayList<>();
String arr[] = str.split("");
for (String s : arr) {
holdAllInputs.add(s);
}
}
As you expect it doesn't give the right result. How can it be fixed? Or can someone help to writing regular expression to parse it properly as wanted?
As output I get:
(,5, ,+, ,3,), ,*, ,1,2, ,/, ,3
instead of
(,5, ,+, ,3,), ,*, ,12, ,/, ,3
The Regular Expression which helps you here is
"(?<=[-+*/()])|(?=[-+*/()])"
and of course, you need to avoid unwanted spaces.
Here we go,
String expr = "(5 + 3) * 12 / 3";
.
. // Your inputs
.
String arr[] = expr.replaceAll("\\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])");
for (String s : arr)
{
System.out.println("Element : " + s);
}
Please see my expiriment : http://rextester.com/YOEQ4863
Hope it helps.
Instead of splitting the input into tokens for which you don't have a regex, it would be good to move ahead with joining the strings in the List like:
StringBuilder sb = new StringBuilder();
for (String s : userInput)
{
sb.append(s);
}
then use sb.toString() later for comparison. I would not advice String concatenation using + operator details here.
Another approach to this would be to use one of the the StringUtils.join methods in Apache Commons Lang.
import org.apache.commons.lang3.StringUtils;
String result = StringUtils.join(list, "");
If you are fortunate enough to be using Java 8, then it's even easier...just use String.join
String result = String.join("", list);
More details on this approach available here
this makes all the inputs into one string which can then be can be compared against the expression to see if it is equal
String x = "";
for(int i = 0; i < holdAllInputs.length; i++){
x = x + holdAllInputs.get(i);
}
if(expr == x){
//do something equal
}else{
//do something if not equal
}
I'm trying to separate the arrays and variables from an expression so that I can populate two ArrayLists with either array names or variables. I am using StringTokenizer. I have the expression broken down, but I am having trouble determining which tokens are array names and which are variables.
public void buildSymbols() {
String s = expr; // input from different part of the program
StringTokenizer st = new StringTokenizer(s, "+-*/[]() ");
while(st.hasMoreElements()){
String temp = st.nextToken();
System.out.println(temp);
}
}
I print temp just to make sure that the expression is being separated, but given an expression such as (varx + vary * varz[(vara + varb[(a + b) * 33])]) / 55 I don't know how to tell that varz and varb are array names, while varx, vary, vara, a, and b are variables.
Any ideas how to do this?
I agree wih EJP: The correct solution would be a specific parser. But if you would be content to recognize which delimitter was found by each call to StringTokenizer.nextToken, you can tell StringTokenizer to return also the delimitters. Also, you'll need to retrieve the next delimitter on every current token (as a lookahead). To do that, it's better to store all the tokens in a list:
public void buildSymbols() {
String s = expr; // input from different part of the program
StringTokenizer st = new StringTokenizer(s, "+-*/[]() ", true);
Set<String> delimiters=new HashSet<String>(Arrays.asList(new String[]{"+","-","*","/","[","]","(",")"," "}));
List<Object> tokens=Collections.list(st);
for(int i=0;i<tokens.size();i++){
String temp = tokens.get(i).toString();
if (delimiters.contains(temp))
{
// It is a delimiter
}
else
{
// It is a term
boolean isAnArray=(isNextTokenAnOpenBracket(tokens, i));
...
}
System.out.println(temp);
}
}
private boolean isNextTokenAnOpenBracket(List<Object> tokens, int currentIndex)
{
return (currentIndex < tokens.size() && "[".equals(tokens.get(1 + currentIndex)));
}
Try the String .split() method. It is an alternative to string tokenizer. You can split a string into an array of smaller strings split by a delimiter, just like StringTokenizer. However, you could do it two separate times, the first being with brackets, and the second with the other symbols. Then you know that the last index of your String arrays are the names of Arrays!
String s = expr;
String[] brackSplit = s.split("\\[");
for (String str : brackSplit) {
String[] finalSplit = str.split("*+-/()");
//finalSplit[finalSplit.length - 1] = Array Name!
}
NOTE: StringTokenizer is becoming deprecated with the new version of Java. The string split() method has become the new "recommended" way of splitting strings by delimiters.
I've got a question about making a save function.
I'm trying to have a string be saved as a single file to set specific settings on a game. So saveFile would read "002007...", having 002 be a player's location, then 007 a player's level, for example.
I understand how to compile the various variables into a single string, but how would I return it to individual variables?
You better go with SQLite or SharedPreferences if you really want to save settings for a game on Android.
On the other hand, if you have to stick with saving a String on a file, you might want to use a delimiter(ie \r\n or # or | would do it) between numbers. So while parsing back delimiters will help you a lot, but beware when things get complicated a single String won't do the thing nicely. Then you might want to use JSON (for simplicity I would prefer gson) to encode your settings into one String and vice verse.
You could use a delimiter between the values like this:
int location = 02;
int level = 3;
int powerUps = 46;
... and so on
String saveString = location + "#" + level + "#" + powerUps + "#" + ...
Then to load the String back into variables:
String[] values = saveString.split("#");
location = values[0];
level = values[1];
powerUps = values[2];
... and so on
My advice is to check out Shared Preferences and you can read Android's documentation on it here.
If you did want to use your single String, file method, I suggest using delimiters. That simply means to put commas, or other types of delimeters in between different integer values. Instead of "002007", save it as "002,007". Example:
String s = "002,007"
String[] values = s.split(","); // values[0] is "002" and values[1] is "007"
Using the .split(String) command will return a String array with each element in the array containing parts of the String that was split up by the parameter, in this case: ,
If you wanted to separate values per person, something like this could be done:
String s = "002,007;003,008";
String[] people = s.split(";"); // people[0] is "002,007", people[1] is "003,004"
String[][] person = new String[people.length][people[0].split(",").length];
for (int i = 0; i < people.length; i++)
{
person[i] = people[i].split(",");
}
Here is what the array would then contain:
person[0][0] is "002"person[0][1] is "007" person[1][0] is "003" person[1][1] is "008"
// print it for your own testing
for (String ppl[] : person)
{
for (String val : ppl)
{
System.out.print(val + " ");
}
System.out.println("");
}