String elimination with exception? - android

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());
}

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);

Split datetime from string 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());
}

add double quotes in string using android

I have string in forloop, I want add that in to another string like the given format
for (int i = 0; i < profiles.length(); i++) {
JSONObject c = profiles.getJSONObject(i);
String admnno = c.getString(TAG_ADMNNO);
}
The result should be like this
"Rajesh", "Mahesh", "Vijayakumar"
or
final CharSequence[] items = {"Rajesh", "Mahesh", "Vijayakumar"};
The adminno should be in double quotes and following comma. Its in android doin Background()
Use \" for this
For example String str="\"Rajesh\""
Try this,
if (TextUtils.isEmpty(string))
return "";
final int lastPos = string.length() - 1;
if (lastPos < 0 || (string.charAt(0) == '"' && string.charAt(lastPos) == '"'))
return string;
return "\"" + string + "\"";
Another option is to use Kotlin's multiline strings. Especially useful when you need hardcode big JSON for UTests:
val jsonString = """
{
"string_key": "value",
"boolean_key": true
}
"""
You can also try this
var id = "\"id\": \""
Output = "id": "
You have to escape the quote using \" like below:
public static String getQuotedString(String sample){
return "\"".concat(sample).concat("\"");
}
In Kotlin, you can use a variable value like this way
val searchText = "Android"
textview.text = "5 articles found for \"$searchText\""
For fixed string:
String str="5 articles found for \"IOS\" "
value is equal for
5 articles found for "IOS"

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.

Removing spaces from string

I'm trying to remove all the spaces from a string derived from user input, but for some reason it isn't working for me. Here is my code.
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonGo:
String input = EditTextinput.getText().toString();
input = String.replace(" ", "");
url = ur + input + l;
Intent myIntent = new Intent(start.this, Main.class);
myIntent.putExtra("URL", url);
start.this.startActivity(myIntent);
break;
}
}
String input = EditTextinput.getText().toString();
input = input.replace(" ", "");
Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim:
input = input.trim();
When I am reading numbers from contact book, then it doesn't worked
I used
number=number.replaceAll("\\s+", "");
It worked and for url you may use
url=url.replaceAll(" ", "%20");
I also had this problem. To sort out the problem of spaces in the middle of the string this line of code always works:
String field = field.replaceAll("\\s+", "");
Try this:
String urle = HOST + url + value;
Then return the values from:
urle.replace(" ", "%20").trim();
String res =" Application "
res=res.trim();
o/p: Application
Note: White space ,blank space are trim or removed
Using kotlin you can write like:
val resultStr = yourString.replace(" ", "")
Example:
val yourString = "Android Kotlin"
val resultStr = yourString.replace(" ", "")
Result: AndroidKotlin

Categories

Resources