Java: Get Float and String value from a String - java

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

Related

Mask part of the String data which is of different lengths using Java

I am in need to mask PII data for my application. The PII data will be of String format and of variable lengths, as it may include name, address, mail id's etc.
So i need to mask these data before logging them, it should not be a full mask instead, if the length of string is less than or equal to 8 characters then mask the first half with "XXX etc.."
If the length is more than 8 then mask the first and last portion of the string such that only the mid 5 characters are visible.
I know we can do this using java sub-stringa nd iterating over the string, but want to know if there is any other simple solution to address this.
Thanks in advance
If you are using Apache Commons, you can do like
String maskChar = "*";
//number of characters to be masked
String maskString = StringUtils.repeat( maskChar, 4);
//string to be masked
String str = "FirstName";
//this will mask first 4 characters of the string
System.out.println( StringUtils.overlay(str, maskString, 0, 4) );
You can check the string length before generating maskString using if else statement.
You can use this function; change the logic of half's as per your needs:
public static String maskedVariableString(String original)
{
String maskedString = null;
if(original.length()<9)
{
int half = original.length()/2;
StringBuilder sb =new StringBuilder("");
for(int i=0;i<(original.length()-half);i++)
{
sb.append("X");
}
maskedString = original.replaceAll("\\b.*(\\d{"+half+"})", sb.toString()+"$1");
}
else
{
int maskLength = original.length()-5;
int firstMaskLength = maskLength/2;
int secondMaskLength = maskLength-firstMaskLength;
StringBuilder sb =new StringBuilder("");
for(int i=0;i<firstMaskLength;i++)
{
sb.append("X");
}
String firstMask = sb.toString();
StringBuilder sb1 =new StringBuilder("");
for(int i=0;i<secondMaskLength;i++)
{
sb1.append("X");
}
String secondMask = sb1.toString();
maskedString = original.replaceAll("\\b(\\d{"+firstMaskLength+"})(\\d{5})(\\d{"+secondMaskLength+"})", firstMask+"$2"+secondMask);
}
return maskedString;
}
Explanation:
() groups the regular expression and we can use $ to access this group($1, $2,$3).
The \b boundary helps check that we are the start of the digits (there are other ways to do this, but here this will do).
(\d{+half+}) captures (half) no of digits to Group 1. The same happens in the else part also.

convert string to int in java

i have a string that has a int value in it. i just want to extract the int value from the string and print.
String str="No. of Days : 365";
String daysWithSplChar = str.replaceAll("[a-z][A-Z]","").trim();
char[] ch = daysWithSplChar.toCharArray();
StringBuffer stb = new StringBuffer();
for(char c : ch)
{
if(c >= '0' && c <= '9')
{
stb.append(c);
}
}
int days = Integer.ParseInt(stb.toString());
is there any better way than this. please let me know.
try String.replaceAll
String str = "No. of Days : 365";
str = str.replaceAll(".*?(\\d+).*", "$1");
System.out.println(str);
you will get
365
Another way of using regex (other than the way suggested by #EvgeniyDorofeev) which is closer to what you did:
str.replaceAll("[^0-9]",""); // give you "365"
which means, replace everything that is not 0-9 with empty string (or, in another word, remove all non-digit characters)
This is meaning the same, just a matter of taste which one is more comfortable to you:
str.replaceAll("\\D",""); // give you "365"
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
This will get you the integer
following code gives you integer value
String str = "No. of Days : 365";
str = str.replaceAll(".*?(\\d+)", "$1");
System.out.println(str);
Integer x = Integer.valueOf(str);//365 in integer type
System.out.println(x+1);//output 366

What's the most concise way in Java to get the "Alpha" out of "AlphaSuffix"?

If I have a string such as one of the following:
AlphaSuffix
BravoSuffix
CharlieSuffix
DeltaSuffix
What is the most concise Java syntax to transform AlphaSuffix into Alpha into BravoSuffix into Bravo?
Use a simple regexp to delete the suffix:
String myString = "AlphaSuffix";
String newString = myString.replaceFirst("Suffix$", "");
Chop it off.
String given = "AlphaSuffix"
String result = given.substring(0, given.length()-"Suffix".length());
To make it even more concise, create a utility method.
public static String chop(String value, String suffix){
if(value.endsWith(suffix)){
return value.substring(0, value.length() - suffix.length());
}
return value;
}
In the utility method, I've added a check to see if the suffix is actually at the end of the value.
Test:
String[] sufs = new String[] {
"AlphaSuffix",
"BravoSuffix",
"CharlieSuffix",
"DeltaSuffix"
};
for (int i = 0; i < sufs.length; i++) {
String s = chop(sufs[i], "Suffix");
System.out.println(s);
}
Gives:
Alpha
Bravo
Charlie
Delta
if suffixes are all different/unkown you can use
myString.replaceFirst("^(Alpha|Bravo|Charlie|Delta|...).*", "$1");

Remove last set of value from a comma separated string in java

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

Converting a string to an integer on Android

How do I convert a string into an integer?
I have a textbox I have the user enter a number into:
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
And the value is assigned to the string hello.
I want to convert it to a integer so I can get the number they typed; it will be used later on in code.
Is there a way to get the EditText to a integer? That would skip the middle man. If not, string to integer will be just fine.
See the Integer class and the static parseInt() method:
http://developer.android.com/reference/java/lang/Integer.html
Integer.parseInt(et.getText().toString());
You will need to catch NumberFormatException though in case of problems whilst parsing, so:
int myNum = 0;
try {
myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());
Use regular expression:
String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""));
output:
i=1234;
If you need first number combination then you should try below code:
String s="abc123xyz456";
int i=NumberFormat.getInstance().parse(s).intValue();
output:
i=123;
Use regular expression:
int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));
output:
i=123;
j=123;
k=123;
Use regular expression is best way to doing this as already mentioned by ashish sahu
public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}
Try this code it's really working.
int number = 0;
try {
number = Integer.parseInt(YourEditTextName.getText().toString());
} catch(NumberFormatException e) {
System.out.println("parse value is not valid : " + e);
}
Best way to convert your string into int is :
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
int converted=Integer.parseInt(hello);
You should covert String to float. It is working.
float result = 0;
if (TextUtils.isEmpty(et.getText().toString()) {
return;
}
result = Float.parseFloat(et.getText().toString());
tv.setText(result);
You can use the following to parse a string to an integer:
int value=Integer.parseInt(textView.getText().toString());
(1) input: 12 then it will work.. because textview has taken this 12 number as "12" string.
(2) input: "abdul" then it will throw an exception that is NumberFormatException.
So to solve this we need to use try catch as I have mention below:
int tax_amount=20;
EditText edit=(EditText)findViewById(R.id.editText1);
try
{
int value=Integer.parseInt(edit.getText().toString());
value=value+tax_amount;
edit.setText(String.valueOf(value));// to convert integer to string
}catch(NumberFormatException ee){
Log.e(ee.toString());
}
You may also want to refer to the following link for more information:
http://developer.android.com/reference/java/lang/Integer.html
There are five ways to convert
The First Way :
String str = " 123" ;
int i = Integer.parse(str);
output : 123
The second way :
String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123
The Third Way :
String str"123";
int i = new Integer(str);
output "123
The Fourth Way :
String str"123";
int i = Integer.valueOf(Str);
output "123
The Fifth Way :
String str"123";
int i = Integer.decode(str);
output "123
There could be other ways
But that's what I remember now
You can also do it one line:
int hello = Integer.parseInt(((Button)findViewById(R.id.button1)).getText().toString().replaceAll("[\\D]", ""));
Reading from order of execution
grab the view using findViewById(R.id.button1)
use ((Button)______) to cast the View as a Button
Call .GetText() to get the text entry from Button
Call .toString() to convert the Character Varying to a String
Call .ReplaceAll() with "[\\D]" to replace all Non Digit Characters with "" (nothing)
Call Integer.parseInt() grab and return an integer out of the Digit-only string.
The much simpler method is to use the decode method of Integer so for example:
int helloInt = Integer.decode(hello);
Kotlin
There are available Extension methods to parse them into other primitive types.
"10".toInt()
"10".toLong()
"true".toBoolean()
"10.0".toFloat()
"10.0".toDouble()
"10".toByte()
"10".toShort()
Java
String num = "10";
Integer.parseInt(num );
I have simply change this
int j = Integer.parseInt(user.replaceAll("[\\D]", ""));
into
int j = 1;
AND IT SOLVE MY PROBLEM

Categories