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
Related
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 have a string, such as "4.25GB"
I'd like to get the floating part "4.25"
And get the string part "GB"
How to get the two values respectively in Java.
Thanks.
Try
String s = "4.25GB"
Float value = Float.valueOf(s.replaceAll("[^\\d.]", "")); // remove all non-numeric symbols
String f = s.replaceAll("[0-9]",""); // remove all numbers
To get Number Part: String numberPart = "4.25GB".replaceAll("[^0-9.]", "");
To get String part: String stringPart = "4.25GB".replaceAll("[^A-Za-z]", "");
Use String.replaceAll to first replace all non-digits and dot with "" to get the number then otherwise
You can write a function that will be similar to C# int.TryParse method, and use it in loop on your string, it will only work if you alwayes have a (NUM)(STRING) formation :
boolean tryParse(String value)
{
try
{
Integer.parseInt(value);
return true;
} catch(NumberFormatException e)
{
return false;
}
}
Use split/ substring concept. divide the string like below:
String Str = new String("4.25GB");
for (String retval: Str.split("G")){
System.out.println(retval);
}
//or u can use
String[] r = s.split("(?=\\p{Upper})");
You could use public String substring(int beginIndex, int endIndex)
String start = "4.25GB";
String numbers = start.substring(0,4);
String letters = start.substring(4,6);
Read more about substrings and how to use them here
Tested, works:
String str = "4.25GB" ;
String parts[] = str.split("(?i)(?<=\\d)(?=[a-z])|(?<=[a-z])(?=\\d)");
float number = Float.parseFloat(parts[0]) ;
String string = parts[1] ;
System.out.println(number); //4.25
System.out.println(string); //GB
You can use regular expression like this :
String s = "4.25GB";
String num = s.replaceAll("[^0-9.]", "");
System.out.println(num);
String str = s.replaceAll("[0-9.]", "");
System.out.println(str);
wish help you.
That depends on what "such as" means. Are all the strings in the format "x.xxGB"? If that's the case, then you can use substring(), as you know the exact number of 'float' chars and 'suffix' chars.
String theStr = "x.xxGB";
String numStr = theStr.substring(0, 4); // grab first 4 chars: "x.xx"
float numFloat = Float.parseFloat(numStr);
String suffix = theStr.substring(5); // or .substring(5, 7); if you know the exact length
If it's more variable than that, it gets more complicated. If you don't know the length of the leading number string, you'd have to check the first part as a valid float, with perhaps the easiest way to be gathering characters as the start and checking each succession as a valid float, with all the rest being considered a suffix. Maybe something like this (pseudocode-ish):
String theStr = "324.994SUFFIX"; // SomeArbitraryNumberAndSuffixString
String currNumStr = "";
Boolean bHaveFloat = true;
for (int i = 1; i < theStr.length(); i++){
String testStr = theStr.substring(0, i);
try{
float f = Float.parseFloat(testStr);
} catch (NumberFormatException nfe){
// handle the exception, printStackTrace, etc...
// failed so No longer have Valid String...
break;
}
currNumStr = testStr;
}
// currNumStr now has the valid numberString
I want to evaluate String like "[1,5] [4,5] [10,6]" in in array.
I'm not quite familiar with the Java regex and the syntax.
String game = "[1,5] [4,5] [10,6]"
Pattern splitter = Pattern.compile("\\[|,|\\]");
splitter.matcher(game);
public String [] gameArray = null;
gameArray = splitter.split(game);
I want to to iterate over each pair of array such as : [0][0] => 1; [0][1] => 5
If you put
StringTokenizer st = new StringTokenizer(game, "[,] ");
while (st.hasMoreTokens())
{
currentNumber = Integer.parseInt(st.nextToken());
// fill array with it
}
It should be what you need, if I understood well
For this purpose you need to split your string.
first of all you need to split on space and after that you need to split on ,(comma).and your third step will be remove brackets So at the end you will get you string into array.
Try,
String game = "[1,5] [4,5] [10,6]";
String[] arry=game.substring(1, game.length()-1).split("\\] +\\[");
List<String[]> twoDim=new ArrayList<>();
for (String string : arry) {
String[] twoArr=string.split(",");
twoDim.add(twoArr);
}
String[][] twoArr=twoDim.toArray(new String[0][0]);
System.out.println(twoArr[0][0]); // 1
System.out.println(twoArr[0][1]); // 5
I need to get the unique name from a string and concatenate with an integer in java.So I want to take first letter of the string and increment that letter with an integer.
Example: tenant name:
"ani,raj,rob" and i need to get the
schema name like a001,r001,r002
here r value will be incremented because of repetition.So I request you to help me find answer for this.I am getting the first letter from a string but I need to concatenate that with an integer.
String name = new String(tenantName);
char sc=tenantName.charAt(0);
String whereClause="tenant_id= select max(tenant_id) from tenant_connection_details
tcd1 where schema_name like'"+sc+"%'";
tenantList= tenantImpl.getAllTenantsByWhereClause(whereClause);
List<String> myNames = new ArrayList<String>();
myNames.add("ani");
myNames.add("raj");
myNames.add("rob");
myNames.add("jigar");
int counter=1;
for(String str:myNames){
System.out.println(str.charAt(0)+String.format("%04d", i));
counter++;
}
if i understand you correctly, it should be something like this (not safe or checked or anything!!):
private List<String> list = new ArrayList<String>();
private void strangeConcat(String name){
int index = 1;
while(this.list.contains(String.valueOf(name.charAt(0))
+ this.getThreeDigitIndex(index))){
index++;
}
this.list.add(String.valueOf(name.charAt(0)) + this.getThreeDigitIndex(index));
}
Something like the following:
char sc=tenantName.charAt(0); // May use Character.toLowerCase() here, if only lowercase letters are allowed
String whereClause="tenant_id= select max(tenant_id) from tenant_connection_details
tcd1 where schema_name like'"+sc+"%'";
tenantList= tenantImpl.getAllTenantsByWhereClause(whereClause);
int number = tenentList.size() + 1;
String result = Character.toString(sc) + String.format("%04d", number);
I wan to remove the last set of data from string using java.
For example I have a string like A,B,C, and I want to remove ,C, and want to get the out put value like A,B . How is it possible in java? Please help.
String start = "A,B,C,";
String result = start.subString(0, start.lastIndexOf(',', start.lastIndexOf(',') - 1));
Here is a fairly "robust" reg-exp solution:
Pattern p = Pattern.compile("((\\w,?)+),\\w+,?");
for (String test : new String[] {"A,B,C", "A,B", "A,B,C,",
"ABC,DEF,GHI,JKL"}) {
Matcher m = p.matcher(test);
if (m.matches())
System.out.println(m.group(1));
}
Output:
A,B
A
A,B
ABC,DEF,GHI
Since there may be a trailing comma, something like this (using org.apache.commons.lang.StringUtils):
ArrayList<String> list = new ArrayList(Arrays.asList(myString.split()));
list.remove(list.length-1);
myString = StringUtils.join(list, ",");
You can use String#lastIndexOf to find the index of the second-to-last comma, and then String#substring to extract just the part before it. Since your sample data ends with a ",", you'll need to use the version of String#lastIndexOf that accepts a starting point and have it skip the last character (e.g., feed in the string's length minus 1).
I wasn't going to post actual code on the theory better to teach a man to fish, but as everyone else is:
String data = "A,B,C,";
String shortened = data.substring(0, data.lastIndexOf(',', data.length() - 2));
You can use regex to do this
String start = "A,B,C,";
String result = start.replaceAll(",[^,]*,$", "");
System.out.println(result);
prints
A,B
This simply erases the the 'second last comma followed by data followed by last comma'
If full String.split() is not possible, the how about just scanning the string for comma and stop after reaching 2nd, without including it in final answer?
String start = "A,B";
StringBuilder result = new StringBuilder();
int count = 0;
for(char ch:start.toCharArray()) {
if(ch == ',') {
count++;
if(count==2) {
break;
}
}
result.append(ch);
}
System.out.println("Result = "+result.toString());
Simple trick, but should be efficient.
In case you want last set of data removed, irrespective of how much you want to read, then
start.substring(0, start.lastIndexOf(',', start.lastIndexOf(',')-1))
Another way to do this is using a StringTokenizer:
String input = "A,B,C,";
StringTokenizer tokenizer = new StringTokenizer(input, ",");
String output = new String();
int tokenCount = tokenizer.countTokens();
for (int i = 0; i < tokenCount - 1; i++) {
output += tokenizer.nextToken();
if (i < tokenCount - 1) {
output += ",";
}
}
public string RemoveLastSepratorFromString(string input)
{
string result = input;
if (result.Length > 1)
{
result = input.Remove(input.Length - 1, 1);
}
return result;
}
// use from above method
string test = "1,2,3,"
string strResult = RemoveLastSepratorFromString(test);
//output --> 1,2,3