I am having a particular pattern of string
page0001
page0002
.
.
.
pageMN23
pageMN24
.
page0100
page0101
and so on
I have to remove "page" and zero's after that and then pick up the page number from that.
and stroe that value. Here it will return both integer and string value for example "3","4" ,"MN23", MN24".
What can be used so that correct value return and it get store in correctly.
test = test.replace("page", "");
int x = Integer.parseInt(test);
Just replace all the occurrences of "page" with an empty string, then Integer.parseInt() takes care of the rest.
Use this:
String test = "page0100";
boolean flag = false;
int pageNo;
try {
test = test.replaceAll("page0*", ""); //Note the meta character * after 0. It removes all zeros exists after `page` string and before any non zero digit.
pageNo = Integer.parseInt(test);
} catch (NumberFormatException e) {
// If NumberNumberFormatException caught here then `test` is string
// NOT valid integer
flag = true;
}
if (flag == false) {
// Page Number is string
// Use `test` variable here
} else {
// Page Number is integer
// Use `pageNo` variable here
}
Related
I'm trying to write a method that checks if a given string only contains these {([])} characters.
// Test strings
String S = "{U}" // should give FALSE
String S = "[U]" // should give FALSE
String S = "U" // should give FALSE
String S = "([)()]" // should give TRUE
I've tried:
if(S.matches("[{(\\[\\])}]")) {
return 1;
}
But this returns never true.
String.matches() matches the entire string against the pattern. The pattern you are trying is failing because it only matches a single character - for example, "{".matches("[{(\\[\\])}]") would return true. You need to add a repeat to your regex - either * if you want to match empty strings, or + if the string must contain at least one character, like so:
if(S.matches("[{(\\[\\])}]+")) {
return 1;
}
if(S.matches("^[{(\\[\\])}]+$")) {
return 1;
}
^ - beginning of the line
[]+ - characters contained in character class [] ONE OR MORE times
$ - end of the line
If you want to create a method (as you've mentioned in question), you might want to consider creating such method returning boolean (note that returning boolean (true or false) is not equal to returning 1 or 0 in Java):
public boolean checkIfContainsOnlyParenthesis(String input) {
return input.matches("^[{(\\[\\])}]+$");
}
If your intention was to return 1 when condition is fulfilled and - for example - 0, when it's not, you need to change return value of that method toint:
public int checkIfContainsOnlyParenthesis(String input) {
if(input.matches("^[{(\\[\\])}]+$")) {
return 1;
} else {
return 0;
}
}
That way you can pass your S string as argument of that method like this:
checkIfContainsOnlyParenthesis(S);
My program sets a numeric value to an editText field..I am trying to convert the edittext values to an integer..I have failed in all the attempts i have tried..Here is how the editText field receives the value:
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
totalAmount[0] += dogExpenditure.getAmount();
textView3.setText(Integer.toString(totalAmount[0] ));
}
}
textView3.setText(Integer.toString(totalAmount[0] I am doing this because the totalAmount[0] cannot be accessed anywhere else other than inside that program so i decided to pull it from the editText(not sure about this) though i havent succeeded. i get java.lang.NumberFormatException: Invalid int: "" error:
Here is how i tried :
String diff = String.valueOf(textView3.getText());
Integer x = Integer.valueOf(diff);
String saley = String.valueOf(textView5.getText());
Integer v = Integer.valueOf(saley);
NB: the textView5 and textView5 are both EditText fields..
A NumberFormatException tell you the String is not a number.
Here, the String is empty so this can't be parse. A solution would be to check for that specific value, like Jesse Hoobergs answer.
But this will not prevent an exception if I input foobar. So the safer solution is to catch the exception. I let you find the correct solution to manager the value if this is not a numerical value.
Integer number;
try{
number = Integer.valueOf(s);
} catch(NumberFormatException nfe){
number = null; //Just an example of default value
// If you don't manage it with a default value, you need to throw an exception to stop here.
}
...
At startup, the value of the editText seems to be an empty string ("").
I think you can best check for empty strings or make sure the initial value isn't an empty string.
String diff = String.valueOf(textView3.getText());
Integer x = null;
if(!diff.trim().isEmpty())
x = Integer.valueOf(diff);
an example that may help you
boolean validInput = true;
String theString = String.valueOf(textView3.getText());
if (!theString.isEmpty()){ // if there is an input
for(int i = 0; i < theString.length(); i++){ // check for any non-digit
char c = theString.charAt(i);
if((c<48 || c>57)){ // if any non-digit found (ASCII chars values for [0-9] are [48-57]
validInput=false;
}
}
}
else {validInput=false;}
if (validInput){// if the input consists of integers only and it's not empty
int x = Integer.parseInt(theString); // it's safe, take the input
// do some work
}
Ok i found out a better way to deal with this..On startup the values are null..so i created another method that handles the edittext fields with a button click after the activity has been initialised..and it works..
private void diffe() {
String theString = String.valueOf(textView3.getText().toString().trim());
String theStringe = String.valueOf(textView5.getText().toString().trim());
int e = Integer.valueOf(theString);
int s = Integer.valueOf(theStringe);
int p = s - e ;
textView2.setText(Integer.toString(p));
}
public static String removeLeadingZeroes(String value):
Given a valid, non-empty input, the method should return the input with all leading zeroes removed. Thus, if the input is “0003605”, the method should return “3605”. As a special case, when the input contains only zeroes (such as “000” or “0000000”), the method should return “0”
public class NumberSystemService {
/**
*
* Precondition: value is purely numeric
* #param value
* #return the value with leading zeroes removed.
* Should return "0" for input being "" or containing all zeroes
*/
public static String removeLeadingZeroes(String value) {
while (value.indexOf("0")==0)
value = value.substring(1);
return value;
}
I don't know how to write codes for a string "0000".
If the string always contains a valid integer the return new Integer(value).toString(); is the easiest.
public static String removeLeadingZeroes(String value) {
return new Integer(value).toString();
}
Stop reinventing the wheel.
Almost no software development problem you ever encounter will be the first time it has been encountered;
instead,
it will only be the first time you encounter it.
Almost every utility method you will ever need has already been written by the Apache project and/or the guava project (or some similar that I have not encountered).
Read the Apache StringUtils JavaDoc page.
This utility is likely to already provide every string manipulation functionality you will ever need.
Some example code to solve your problem:
public String stripLeadingZeros(final String data)
{
final String strippedData;
strippedData = StringUtils.stripStart(data, "0");
return StringUtils.defaultString(strippedData, "0");
}
You could add a check on the string's length:
public static String removeLeadingZeroes(String value) {
while (value.length() > 1 && value.indexOf("0")==0)
value = value.substring(1);
return value;
}
I would consider checking for that case first. Loop through the string character by character checking for a non "0" character. If you see a non "0" character use the process you have. If you don't, return "0". Here's how I would do it (untested, but close)
boolean allZero = true;
for (int i=0;i<value.length() && allZero;i++)
{
if (value.charAt(i)!='0')
allZero = false;
}
if (allZero)
return "0"
...The code you already have
private String trimLeadingZeroes(inputStringWithZeroes){
final Integer trimZeroes = Integer.parseInt(inputStringWithZeroes);
return trimZeroes.toString();
}
You can use below replace function it will work on a string having both alphanumeric or numeric
s.replaceFirst("^0+(?!$)", "")
public String removeLeadingZeros(String digits) {
//String.format("%.0f", Double.parseDouble(digits)) //Alternate Solution
String regex = "^0+";
return digits.replaceAll(regex, "");
}
removeLeadingZeros("0123"); //Result -> 123
removeLeadingZeros("00000456"); //Result -> 456
removeLeadingZeros("000102030"); //Result -> 102030
Convert input to StringBuilder
Use deleteCharAt method to remove character from beginning till non-zero character is found
String trimZero(String str) {
StringBuilder strB = new StringBuilder(str);
int index = 0;
while (strB.length() > 0 && strB.charAt(index) == '0') {
strB.deleteCharAt(index);
}
return strB.toString();
}
You can use pattern matcher to check for strings with only zeros.
public static String removeLeadingZeroes(String value) {
if (Pattern.matches("[0]+", value)) {
return "0";
} else {
while (value.indexOf("0") == 0) {
value = value.substring(1);
}
return value;
}
}
You can try this:
1. If the numeric value of the string is 0 then return new String("0").
2. Else remove the zeros from the string and return the substring.
public static String removeLeadingZeroes(String str)
{
if(Double.parseDouble(str)==0)
return new String("0");
else
{
int i=0;
for(i=0; i<str.length(); i++)
{
if(str.charAt(i)!='0')
break;
}
return str.substring(i, str.length());
}
}
Use String.replaceAll(), like this:
public String replaceLeadingZeros(String s) {
s = s.replaceAll("^[0]+", "");
if (s.equals("")) {
return "0";
}
return s;
}
This will match all leading zeros (using regex ^[0]+) and replace them all with blanks. In the end if you're only left with a blank string, return "0" instead.
int n = 000012345;
n = Integer.valueOf(n + "", 10);
It is important to specify radix 10, else the integer is read as an octal literal and an incorrect value is returned.
public String removeLeadingZeros(String num) {
String res = num.replaceAll("^0+", "").trim();
return res.equals("")? "0" : res;
}
I have found the following to be the simplest and most reliable, as it works for both integers and floating-point numbers:
public static String removeNonRequiredLeadingZeros(final String str) {
return new BigDecimal(str).toPlainString();
}
You probably want to check the incoming string for null and blank, and also trim it to remove leading and trailing whitespace.
You can also get rid of trailing zeros by using:
public static String removeNonRequiredZeros(final String str) {
return new BigDecimal(str).stripTrailingZeros().toPlainString();
}
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 have the following string
ford-focus-albany-ny-v12356-l12205
I'm trying to parse the last two sets of numbers out
12356 and 12205
I'm using the prefix letter to define the id type since the order of those int may very.
v = vehicle id "id length may very"
l = location id "id length may very"
I'd also like to add one may exist without the other. Example
ford-focus-v12356 or albany-ny-l12205
I'm really not sure what the best approach to splitting the string dynamically is, my initial thought was to find the last two - and then try to parse the ints from the prefix. Anybody have any suggestions or a possible example?
String str = "ford-focus-albany-ny-v12356-l12205";
String[] substrings = str.split("-");
for (String arg: substrings) {
if (arg.matches("v[0-9]*")) {
String v = arg.substring(1);
}
else if (arg.matches("l[0-9]*")) {
String l = arg.substring(1);
}
}
You can try it with regex expression and replace like this:
//this will give you 12356
"ford-focus-albany-ny-v12356-l12205".replaceAll( "(.*)(-v)([^-]*)(.*)", "$3" );
//this will give you 12205
"ford-focus-albany-ny-v12356-l12205".replaceAll( "(.*)(-l)([^-]*)(.*)", "$3" );
//this will also give you 12356
"ford-focus-v12356".replaceAll( "(.*)(-v)([^-]*)(.*)", "$3" );
//this will give you 12205
"albany-ny-l12205".replaceAll( "(.*)(-l)([^-]*)(.*)", "$3" );
You can match one or both of them with a simple pattern:
(?:-([vl])(\\d+))(?:-[vl](\\d+))?
The idea behind this pattern is simple: it matches and captures the initial marker -v or -l, followed by a sequence of digits, which are captured into capturing groups.
Pattern p = Pattern.compile("(?:-([vl])(\\d+))(?:-[vl](\\d+))?");
for(String s : new String[] {"ford-focus-albany-ny-v12356-l12205","ford-focus-albany-ny-l12205","ford-focus-albany-ny-v12356"}) {
Matcher m = p.matcher(s);
if (m.find()) {
if (m.group(1).equals("v")) {
System.out.println("verhicle="+m.group(2));
String loc = m.group(3);
if (loc != null) {
System.out.println("location="+loc);
} else {
System.out.println("No location");
}
} else {
System.out.println("No vehicle");
System.out.println("location="+m.group(2));
}
}
}
Here is a demo on ideone.
How about trying to split with String.split("-") and then use the Array returned like this:
String[] result = longString.split("-");
// Get the last number
String lastPrefix = result[result.lenght-1].subString(0, 1);
// Here check the prefix
// try to get number
int lastNumber;
try {
lastNumber = = Integer.parseInt(result[result.lenght-1].subString(1));
} catch (NumberFormatException e) {
// Do something with exception
}
// And now do similar with result.lenght-2