Split datetime from string android - android

I have String s = http://kqxs.net.vn/xo-so-ngay/an-giang-xsag-23-4-2015/
(Using Java android)how to split date string 23-4-2015 from it become two substring:
http://kqxs.net.vn/xo-so-ngay/an-giang-xsag
23-4-2015

Use the substring method
String str = "http://kqxs.net.vn/xo-so-ngay/an-giang-xsag-23-4-2015/";
url = str.substring(0, 43);
date = str.substring(44, 53);

I hope the date will always be on the last. So you can actualy do Java substring take the last 11 char from the end. Because there is "/".
Hard way you can actually do a RegEx to get only a number. But it is not possible if in the URL there is a numerical too.

Try this using regular expressions,
String str = "http://kqxs.net.vn/xo-so-ngay/an-giang-xsag-23-4-2015/";
String regexStr = "\\d{2}-\\d{1,2}-\\d{4}";
Pattern pattern = Pattern.compile(regexStr);
Matcher matcher = pattern.matcher(str);
int startIndex=-1;
// Check all occurrences
while (matcher.find()) {
startIndex = matcher.start();
}
if(startIndex>0){
String firstPart = str.substring(0,startIndex-1);
String secondPart = str.substring(startIndex);
System.out.println("First Part "+firstPart);
System.out.println("Second Part "+secondPart);
}else{
System.out.println("Match Not Found!");
}
Output:-
First Part http://kqxs.net.vn/xo-so-ngay/an-giang-xsag
Second Part 23-4-2015/

Try This code for The Get the date from the String.
String str="fgdfg12°59'50\" Nfr | gdfg: 80°15'25\" Efgd";
String[] spitStr= str.split("\\|");
String numberOne= spitStr[0].replaceAll("[^0-9]", "");
String numberSecond= spitStr[1].replaceAll("[^0-9]", "");
Try this another code
String str=" abc d 1234567890pqr 54897";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
matcher.find();
System.out.println(matcher.group());
}

Related

How to truncate decimal value in a text

So, I need to show a string in UI which has both numbers and text together.
Something like this,
10.289 Mbps
and I wanted to remove .289 and just show 10 Mbps
I tried a lot of options like setting text as
String rounded = String.format("%.0f", speedValue);
But nothing seems to be working for me.
Appreciate any help.
This can be possible in many ways.
Split String
String inputStr = "10.289 Mbps";
String[] splited = inputStr.split(" ");
Double val = Double.parseDouble(splited[0]);
System.out.println("Value : "+val.intValue()+" "+splited[1]);
Regx
Pattern pattern = Pattern.compile("(([0-9]+)(.)?([0-9]+)?) ([A-Z,a-z]+)", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.find())
{
System.out.println("Value : "+matcher.group(2)+" "+matcher.group(5));
}
something like this can work:
string = "10.289 Mbps"
string_list = string.split(" ")
number = string_list[0]
number = float(number)
print(round(number))
basically isolate the number bu removing 'Mbps' then cast it to a float value and round it to get an integer.
try this
String str = "10.289 Mbps";
String[] strArray = str.split(" ");
Long roundedValue = Math.round(Double.valueOf(strArray[0]));
String resultStr = roundedValue.toString() + " " + strArray[1];
System.out.println(resultStr);

String elimination with exception?

String first = "books(32/400)";
String second = first.replaceAll("\\D+", "");
Result is second = 32400. That's OK.
But, I want to this result:
second = 400
If you have fixed structure with slash and bracket try tis
var result=first.substring(first.lastIndexOf("/")+1,first.lastIndexOf(")"));
result=400
Try this regex, you can tweak the pattern to exclude what you do not need.
Regex regEx = new Regex(#"[books()]");
string output = Regex.Replace(regEx.Replace(#"books(32/400)", ""), #"\s+", "");
string result = output.Split('/').Last();
Try it with:
String second = first.substring(first.indexOf("/") + 1, first.indexOf(")"));
use this pattern : "\\d+"
String first = "books(32/400)";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(first);
while (m.find()) {
System.out.println(m.group());
}

How can I effectively replace one or more characters

I have a String separated by commas as follows
1,2,4,6,8,11,14,15,16,17,18
This string is generated upon user input. Suppose the user wants to remove any of the numbers, I have to rebuild the string without the specified number.
If the current string is:
1,2,4,6,8,11,14,15,16,17,18
User intents to remove 1, the final string has to be:
2,4,6,8,11,14,15,16,17,18
I tried to achieve this using the following code:
//String num will be the number to be removed
old = tv.getText().toString(); //old string
newString = old.replace(num+",",""); //will be the new string
This might be working sometimes but it is sure that it won't work for the above example I have shown, if I try to remove the 1, it also removes the last part of 11, because there also exists 1.
well you can use this. Its the most simplest approach i can think of:
//String num will be the number to be removed
old=","+tv.getText().toString()+",";//old string commas added to remove trailing entries
newString=old.replace(","+num+",",",");// will be the new string
newString=newString.substring(1,newString.length()-1); // removing the extra commas added
This would work for what you want to do. I have added a comma at the start and end of your string so that you can also remove the first and last entries too.
You can split the string first and check for the number where you append those value that is not equivalent to the number that will get deleted;
sample:
String formated = "1,2,4,6,8,11,14,15,16,17,18";
String []s = formated.split(",");
StringBuilder newS = new StringBuilder();
for(String s2 : s)
{
if(!s2.equals("1"))
newS.append(s2 + ",");
}
if(newS.length() >= 1)
newS.deleteCharAt(newS.length() - 1);
System.out.println(newS);
result:
2,4,6,8,11,14,15,16,17,18
static public String removeItemFromCommaDelimitedString(String str, String item)
{
StringBuilder builder = new StringBuilder();
int count = 0;
String [] splits = str.split(",");
for (String s : splits)
{
if (item.equals(s) == false)
{
if (count != 0)
{
builder.append(',');
}
builder.append(s);
count++;
}
}
return builder.toString();
}
String old = "1,2,4,6,8,11,14,15,16,17,18";
int num = 11;
String toRemove = "," + num + "," ;
String oldString = "," + old + ",";
int index = oldString.indexOf(toRemove);
System.out.println(index);
String newString = null;
if(index > old.length() - toRemove.length() + 1){
newString = old.substring(0, index - 1);
}else{
newString = old.substring(0, index) + old.substring(index + toRemove.length() -1 , old.length());
}
System.out.println(newString);

Multiply Integers Inside A String By An Individual Value Using Regex

I currently have the code below and it successfully returns all the numbers that are present in a string I have.
An example of the string would be say: 1 egg, 2 rashers of bacon, 3 potatoes.
Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(o1.getIngredients());
while (matcher.find()) {
Toast.makeText(this, "" + matcher.group(), Toast.LENGTH_LONG).show();
}
However, I would like to multiply these numbers by say four and then place them back in the original string. How can I achieve this?
Thanks in advance!
I've never tried this, but I think appendReplacement should solve your problem
Doing arithmetic is a little complicated while doing the find()
Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(test);
int start = 0;
int end = 0;
StringBuffer resultString = new StringBuffer();
while (matcher.find()) {
start = matcher.start();
// Copy the string from the previous end to the start of this match
resultString.append(test.substring(end, start));
// Append the desired new value
resultString.append(4 * Integer.parseInt(matcher.group()));
end = matcher.end();
}
// Copy the string from the last match to the end of the string
resultString.append(test.substring(end));
This StringBuffer will hold the result you are expecting.

How to split this String?

I want to split this string
String info = "0.542008835 meters height from ground";
from this i want to get only two decimals like this 0.54.
by using this i am getting that
String[] _new = rhs.split("(?<=\\G....)");
But i am facing problem here, if string does't contain any decimals like this string
String info = "1 meters height from ground";
for this string i am getting those characters upto first 4 in the split string like 1 me.
i want only numbers to split if it has decimals, How to solve this problem.
if(info.contains("."))
{
String[] _new = rhs.split("(?<=\\G....)");
}
I think you can check by white space after first value. see this
If you get the space then get first character only.
For checking if a string contains whitespace use a Matcher and call it's find method.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
If you want to check if it only consists of whitespace then you can use String.matches:
boolean isWhitespace = s.matches("^\\s*$");
You could use a regex to do this as an alternative to Deepzz's method, this will handle the case where there is a '.' in the later part of the String, I've included an example below. It's not clear from your question is you actually want to remaining part of the String, but you could add a second group to the reg ex to capture this.
public static void main(String[] args) {
final String test1 = "1.23 foo";
final String test2 = "1 foo";
final String test3 = "1.234 foo";
final String test4 = "1.234 fo.o";
final String test5 = "1 fo.o";
getStartingDecimal(test1);
getStartingDecimal(test2);
getStartingDecimal(test3);
getStartingDecimal(test4);
getStartingDecimal(test5);
}
private static void getStartingDecimal(final String s) {
System.out.print(s + " : ");
Pattern pattern = Pattern.compile("^(\\d+\\.\\d\\d)");
Matcher matcher = pattern.matcher(s);
if(matcher.find()) {
System.out.println(matcher.group(1));
} else {
System.out.println("Doesn't start with decimal");
}
}
Assuming the number is always the first part of the string:
String numStr = rhs.split(" ")[0];
Double num = Double.parseDouble(numStr);
After that you can use the String Formatter to get the desired representation of the number.
This will work when you know the String near the numbers, with int and double numbers as well.
String a ="0.542008835 meters height from ground";
String b = a.replace(" meters height from ground", "");
int c = (int) ((Double.parseDouble(b))*100);
double d = ((double)c/100);

Categories

Resources