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);
Related
I want to parse two values from a string in android studio.
I cannot change the data type from web so I need to parse an Intt.The string that I receive from web is
5am-10am.
How can I get these values i.e. 5 and 10 from the string "5am-10am".
Thanks in advance for help.
its work only this kind of format "Xam-Yam".
String value="5am-10am";
value.replace("am","");
value.replace("pm","");//if your string have pm means add this line
String[] splited = value.split("-");
//splited[0]=5
//splited[1]=10
Here is the trick you should use:-
String timeValue="5am-10am";
String[] timeArray = value.split("-");
// timeArray [0] == "5am";
// timeArray [1] == "10am";
timeArray [0].replace("am","");
// timeArray [0] == "5";// what u needed
timeArray [1].replace("am","");
// timeArray [1] == "10"; // what u needed
So, the code below shows step by step how to parse the format you are given. I also added in the steps to use the newly parsed Strings as ints so you can perform arithmetic on them. Hope this helps.
`/*Get the input*/
String input = "5am-10am"; //Get the input
/*Separate the first number from the second number*/
String[] values = input.split("-"); //Returns 'values[5am, 10am]'
/*Not the best code -- but clearly shows what to do*/
values[0] = values[0].replaceAll("am", "");
values[0] = values[0].replaceAll("pm", "");
values[1] = values[1].replaceAll("am", "");
values[1] = values[1].replaceAll("pm", "");
/*Allows you to now use the string as an integer*/
int value1 = Integer.parseInt(values[0]);
int value2 = Integer.parseInt(values[1]);
/*To show it works*/
int answer = value1 + value2;
System.out.println(answer); //Outputs: '15'`
I will use some regex to remove the other String and leave only the numeric data. sample code below:
public static void main(String args[]) {
String sampleStr = "5am-10pm";
String[] strArr = sampleStr.split("-"); // I will split first the two by '-' symbol.
for(String strTemp : strArr) {
strTemp = strTemp.replaceAll("\\D+",""); // I will use this regex to remove all the string leaving only numbers.
int number = Integer.parseInt(strTemp);
System.out.println(number);
}
}
The advantages of this is you don't need to specifically remove "am" or "pm" because all of the other character will be remove and the numbers will only be left.
I think that this way can be the faster. Please consider that the regex doesn't validates so it will parse values as "30am-30pm" for example. Validation comes apart.
final String[] result = "5am-10pm".replaceAll("(\\d)[pa]m", "$1").split("-");
System.out.println(result[0]); // -- 5
System.out.println(result[1]); // -- 10
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
}
}
Split without limits split the entire string but if you set a limit it splits up to that limit by the left. How can I do the same by the right?
"a.b.c".split("[.]", 2); // returns ["a", "b.c"]
I would want
"a.b.c".splitRight("[.]", 2); // to return ["a.b", "c"]
EDIT: I want a general solution that works just like splited but reversed so I add a more complex example
I would want
"a(->)b(->)c(->)d".splitRight("\\(->\\)", 3); // to return ["a(->)b", "c", "d"]
You may use look-ahead match:
"a.b.c".split("[.](?=[^.]*$)")
Here you say "I want to split by only that dot which has no other dots after it".
If you want to split by last N dots, you can generalize this solution in this (even more ugly way):
"dfsga.sdgdsb.dsgc.dsgsdfg.dsdg.sdfg.sdf".split("[.](?=([^.]*[.]){0,3}[^.]*$)");
Replace 3 with N-2.
However I would write a short static method instead:
public static String[] splitAtLastDot(String s) {
int pos = s.lastIndexOf('.');
if(pos == -1)
return new String[] {s};
return new String[] {s.substring(0, pos), s.substring(pos+1)};
}
I would try with something like this:
public List<String> splitRight(String string, String regex, int limit) {
List<String> result = new ArrayList<String>();
String[] temp = new String[0];
for(int i = 1; i < limit; i++) {
if(string.matches(".*"+regex+".*")) {
temp = string.split(modifyRegex(regex));
result.add(temp[1]);
string = temp[0];
}
}
if(temp.length>0) {
result.add(temp[0]);
}
Collections.reverse(result);
return result;
}
public String modifyRegex(String regex){
return regex + "(?!.*" + regex + ".*$)";
}
The regular expression for split is wrapped by another, so for \\., you will get: \\.(?!.*\\..*$), to match and split on last occurance of delimiter. The string is splitted multiple time with this regex, the second element of result array is added to List, next split is done on first element of result array.
The effect of above method for your example string is as expected.
Despite that you said reversing would take to long, hereĀ“s a small programm that reveres the String and splits it by the limit;
static String[] leftSplit(String input, String regex, int limit) {
String reveresedInput = new StringBuilder(input).reverse().toString();
String[] output = reveresedInput.split(regex, limit);
String tempOutput[] = new String[output.length];
for(int i = 0;i<output.length;++i) {
tempOutput[tempOutput.length-i-1] = new StringBuilder(output[i]).reverse().toString();
}
return tempOutput;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(leftSplit("a.b.c", "[.]", 2)));
System.out.println(Arrays.toString(leftSplit("I want to. Split this. by the. right side", "[.]", 2)));
}
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;
}
}