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
}
}
Related
I'm trying to ensure text does not appear outside of the window as the window size cannot be changed.
The image above shows what happens when the string of the order numbers exceeds the length of the window. I'm trying to ensure that when the length of the string of order numbers reaches a certain length, I use regex to make a new line for the next orders.
private String listOfOrders( Map<String, List<Integer> > map, String key )
{
String res = "";
if ( map.containsKey( key ))
{
List<Integer> orders = map.get(key);
for ( Integer i : orders )
{
res += " " + i + ",";
}
} else {
res = "-No key-";
}
return res;
}
}
This is the code to display the text, it works by forming the string res and filling it with the order numbers from the array list.
I found, through researching, a cool little piece of code which replaces a string every set amount of characters with itself plus a new line.
if(res.length() >= W-10)
{
res = res.replaceAll("(.{20})", "$1\n");
}
else
{
res += " " + i + ",";
}
But this has no effect at all. And I also realised that this code can not tell how long each line is because I'm using length to determine the length of each line and not how long each line is between each "\n".
My question is, how do I go about using regex to ensure each line in the string is a certain number of characters long? As my attempt does not work. The above just provides context as to why I want lines in a string a certain legnth.
Thanks!
I need to get the values after "Swap:".
I've already developed a method to get the output from a shell command so I have a string that contains everything you see in the picture but now from the string I want to get ONLY the value after the Swap: How can i do this? These value are variable and can be even all three 0.
Let's say you have the text stored in a String called textContent. Assuming the Swap-line is the last part of your String, then you could do something like this:
int index = textContent.indexOf("Swap:");
index += "Swap:".length();
textContent.subString(index);
Try this:
String[] stringParts = text.substring(text.indexOf("Swap:") + 5).trim().split("( )+");
int[] parts = new int[stringParts.length];
for (int i = 0; i < stringParts.length; i++)
parts[i] = Integer.parseInt(stringParts[i]);
It will fill an integer array will the values after the "Swap" part.
Since you have already stored the output of the shell command, you simply need to do some string manipulation to search and extract the relevant information. The following particular string manipulation methods might be of interest to you: trim(), indexOf(), and substring().
Below is a simple example code on how to extract the value under the total's column using the above String methods:
public class ShellOutput {
public ShellOutput() {
final String extract = "Swap:"; // the keyword to search
String shellOutput = "Swap: 75692 29657 0"; // your shell output
int position = shellOutput.indexOf(extract); // get the position of the Swap: text
if (position != -1) {
String swapLine = shellOutput.substring(position + extract.length()); // remove everything except the swap line
String numbers = swapLine.trim(); // assuming they are spaces, otherwise do some operations to remove tabs if used
int firstSpace = numbers.indexOf(' '); // get the first space or change to a tab character if it is used
String totalNumber = numbers.substring(0, firstSpace); // remove up to the first found after the number
System.out.println("Total = " + totalNumber);
} else {
System.out.println("No '" + extract + "' segment found.");
}
}
public static void main(String[] args) {
new ShellOutput();
}
}
Output: Total = 75692
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;
}
}
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("");
}
I have strings separated by comma and need split by comma and need the last value only.I've tried to separated values but i want to help to get the only last string after comma.
My expectation is :
case 1 : if String is "stack", then I need only stack
case 2 : if String is "stack,over", then I need only over
case 3 : if String is "stack,over,flow", then I need only flow.
The same scenario for unlimited strings.
public class Test {
public static void main(String as[])
{
String data = "1,Diego Maradona,Footballer,Argentina";
String[] items = data.split(",");
for (String item : items)
{
System.out.println("item = " + item);
}
}
}
You can directly get the String at the last index.
String[] items = data.split(",");
String lastString = items[items.length - 1]; // String at the last index
Or you can also use the String#substring(beginIndex) and the String#lastIndexOf(char) methods to get it without splitting the String. Something like this
String lastString = data.substring(data.lastIndexOf(',') + 1);
// +1 because you need to get the string after the last comma
data.substring(data.lastIndexOf(",") + 1);
or
items[items.length - 1];
s.substring(s.lastIndexOf(",") + 1);
String lastItem = data.substring(data.lastIndexOf(",") + 1);
System.out.println(lastItem);