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();
}
Related
I need to create a recursive method that takes a String parameter.
I need to verify that the first letter in the string is a lowercase character, and then verify that everything that comes after the first letter is a number.
So it should be like this a1234.
I've tried creating a base case, smaller base case, and a general case, but can't seem to figure out the right way to style it:
public void digitCheck(String s) {
if () //To Check that first character is a letter
else if ()To check that everything after the first letter is a number
else //Invalid
}
I need the code to report whether it's a valid string if the first character is a lower case letter and everything after that is a number.
Example:
a123 -> valid.
ab123 -> invalid.
Use the String.matches() method:
boolean valid = s.matches(".\\d+");
For solving this problem with recursion for your pattern you can do:
start from the end and
check the last element
remove the last element
call all remaining part
It should be checking until one element will be passed to the method -> make final validation if it is a lower letter.
Also, StringUtils class is used from commons lang library.
Here is code snippet:
public class StringValidationDemo {
public boolean validateStringRecursive(String str) {
if (str.length() == 1) {
return StringUtils.isAlpha(str) && StringUtils.isAllLowerCase(str);
}
String lastIndex = str.substring(str.length() - 1);
return StringUtils.isNumeric(lastIndex)
&& validateStringRecursive(str.substring(0, str.length() - 1));
}
public static void main(String[] args) {
List<String> words = Arrays.asList("a123", "ab123", "123ab", "A123", "aaa", "123");
StringValidationDemo demo = new StringValidationDemo();
for (String word : words) {
System.out.printf("validation for: %s = %s\n",
word, demo.validateStringRecursive(word));
}
}
}
Output:
validation for: a123 = true
validation for: ab123 = false
validation for: 123ab = false
validation for: A123 = false
validation for: aaa = false
validation for: 123 = false
I think you could ommit the first character in the string, and then just check with Integer.parseInt(String). so it would look something like:
public static boolean isNumeric(String strNum) {
try {
double d = Integer.parseInt(String);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
public void DoStuff(String string){
if (isNumeratic(string.substring(1)) //ommits first
{
///yourstuff
}
}
I am replacing a character in a string. There has to be a better way to do this, right?
public static String eqEq(String stringIn) {
char[] stringArray;
stringArray = stringIn.toCharArray();
for (int i = 0; i < stringIn.length(); i++){
if(stringArray[i] == '='){
stringArray[i] = '?';
}
}
String sReturn = new String(stringArray);
return sReturn;
}
Something wrong with replace()?
public static String eqEq(String stringIn) {
return stringIn.replace('=', '?');
}
Note that replace() replaces all occurrences, but uses plain text search/replacements, unlike replaceAll() which is the regex version of replace().
Also note the replace() has two versions: One version that has char parameters (used here), and another that has String parameters in case you want to search/replace more than one character.
You could try String#replace, for example
stringIn = stringIn.replace('=', '?');
You could even use String#repalceAll if you want to use a regular expression instead.
You could even use a StringBuilder
StringBuilder sb = new StringBuilder(value);
int index = -1;
while ((index = sb.indexOf("=")) != -1) {
sb.replace(index, index + 1, "?");
}
The choice is yours
You can use the replace or replaceAll methods on the String class, as follows:
public static String eqEq(String stringIn) {
stringIn.replace("=", "?");
}
OR
public static String eqEq(String stringIn) {
stringIn.replaceAll("=", "?");
}
See a live example of this code running (using replaceAll) on a sample string.
I'm using codingbat.com to get some java practice in. One of the String problems, 'withoutString' is as follows:
Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive).
You may assume that the remove string is length 1 or more. Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".
This problem can be found at: http://codingbat.com/prob/p192570
As you can see from the the dropbox-linked screenshot below, all of the runs pass except for three and a final one called "other tests." The thing is, even though they are marked as incorrect, my output matches exactly the expected output for the correct answer.
Here's a screenshot of my output:
And here's the code I'm using:
public String withoutString(String base, String remove) {
String result = "";
int i = 0;
for(; i < base.length()-remove.length();){
if(!(base.substring(i,i+remove.length()).equalsIgnoreCase(remove))){
result = result + base.substring(i,i+1);
i++;
}
else{
i = i + remove.length();
}
if(result.startsWith(" ")) result = result.substring(1);
if(result.endsWith(" ") && base.substring(i,i+1).equals(" ")) result = result.substring(0,result.length()-1);
}
if(base.length()-i <= remove.length() && !(base.substring(i).equalsIgnoreCase(remove))){
result = result + base.substring(i);
}
return result;
}
Your solution IS failing AND there is a display bug in coding bat.
The correct output should be:
withoutString("This is a FISH", "IS") -> "Th a FH"
Yours is:
withoutString("This is a FISH", "IS") -> "Th a FH"
Yours fails because it is removing spaces, but also, coding bat does not display the correct expected and run output string due to HTML removing extra spaces.
This recursive solution passes all tests:
public String withoutString(String base, String remove) {
int remIdx = base.toLowerCase().indexOf(remove.toLowerCase());
if (remIdx == -1)
return base;
return base.substring(0, remIdx ) +
withoutString(base.substring(remIdx + remove.length()) , remove);
}
Here is an example of an optimal iterative solution. It has more code than the recursive solution but is faster since far fewer function calls are made.
public String withoutString(String base, String remove) {
int remIdx = 0;
int remLen = remove.length();
remove = remove.toLowerCase();
while (true) {
remIdx = base.toLowerCase().indexOf(remove);
if (remIdx == -1)
break;
base = base.substring(0, remIdx) + base.substring(remIdx + remLen);
}
return base;
}
I just ran your code in an IDE. It compiles correctly and matches all tests shown on codingbat. There must be some bug with codingbat's test cases.
If you are curious, this problem can be solved with a single line of code:
public String withoutString(String base, String remove) {
return base.replaceAll("(?i)" + remove, ""); //String#replaceAll(String, String) with case insensitive regex.
}
Regex explaination:
The first argument taken by String#replaceAll(String, String) is what is known as a Regular Expression or "regex" for short.
Regex is a powerful tool to perform pattern matching within Strings. In this case, the regular expression being used is (assuming that remove is equal to IS):
(?i)IS
This particular expression has two parts: (?i) and IS.
IS matches the string "IS" exactly, nothing more, nothing less.
(?i) is simply a flag to tell the regex engine to ignore case.
With (?i)IS, all of: IS, Is, iS and is will be matched.
As an addition, this is (almost) equivalent to the regular expressions: (IS|Is|iS|is), (I|i)(S|s) and [Ii][Ss].
EDIT
Turns out that your output is not correct and is failing as expected. See: dansalmo's answer.
public String withoutString(String base, String remove) {
String temp = base.replaceAll(remove, "");
String temp2 = temp.replaceAll(remove.toLowerCase(), "");
return temp2.replaceAll(remove.toUpperCase(), "");
}
Please find below my solution
public String withoutString(String base, String remove) {
final int rLen=remove.length();
final int bLen=base.length();
String op="";
for(int i = 0; i < bLen;)
{
if(!(i + rLen > bLen) && base.substring(i, i + rLen).equalsIgnoreCase(remove))
{
i +=rLen;
continue;
}
op += base.substring(i, i + 1);
i++;
}
return op;
}
Something things go really weird on codingBat this is just one of them.
I am adding to a previous solution, but using a StringBuilder for better practice. Most credit goes to Anirudh.
public String withoutString(String base, String remove) {
//create a constant integer the size of remove.length();
final int rLen=remove.length();
//create a constant integer the size of base.length();
final int bLen=base.length();
//Create an empty string;
StringBuilder op = new StringBuilder();
//Create the for loop.
for(int i = 0; i < bLen;)
{
//if the remove string lenght we are looking for is not less than the base length
// and the base substring equals the remove string.
if(!(i + rLen > bLen) && base.substring(i, i + rLen).equalsIgnoreCase(remove))
{
//Increment by the remove length, and skip adding it to the string.
i +=rLen;
continue;
}
//else, we add the character at i to the string builder.
op.append(base.charAt(i));
//and increment by one.
i++;
}
//We return the string.
return op.toString();
}
Taylor's solution is the most efficient one, however I have another solution that is a naive one and it works.
public String withoutString(String base, String remove) {
String returnString = base;
while(returnString.toLowerCase().indexOf(remove.toLowerCase())!=-1){
int start = returnString.toLowerCase().indexOf(remove.toLowerCase());
int end = remove.length();
returnString = returnString.substring(0, start) + returnString.substring(start+end);
}
return returnString;
}
#Daemon
your code works. Thanks for the regex explanation. Though dansalmo pointed out that codingbat is displaying the intended output incorrectly, I through in some extra lines to your code to unnecessarily account for the double spaces with the following:
public String withoutString(String base, String remove){
String result = base.replaceAll("(?i)" + remove, "");
for(int i = 0; i < result.length()-1;){
if(result.substring(i,i+2).equals(" ")){
result = result.replace(result.substring(i,i+2), " ");
}
else i++;
}
if(result.startsWith(" ")) result = result.substring(1);
return result;
}
public String withoutString(String base, String remove){
return base.replace(remove,"");
}
I am attempting to create a method that checks every character in userInput to see if they are present in operatorsAndOperands. The issue is that tempbool is always false for all values.
import java.util.*;
public class stringCalculator
{
private String userInput = null;
String[] operatorsAndOperands = {"1","2","3","4","5","6","7","8","9","0","+","-","*","/"};
public stringCalculator(String newInput)
{
userInput = newInput;
}
public boolean checkInput()
{
boolean ifExists = true;
for(int i=0; i<userInput.length(); i++)
{
char currentChar = userInput.charAt(i);
boolean tempbool = Arrays.asList(operatorsAndOperands).contains(currentChar);
if (tempbool == false)
{
ifExists = false;
}
}
return ifExists;
}
}
This is because you have an array of string objects (which you later convert to a list of string objects), but you are checking a char for presence in that array.
Efficiency is also pretty poor here - converting a fixed array to a list on each iteration takes a lot of unnecessary CPU cycles.
A simple solution to this problem is to put all characters in a string, and then check each incoming character against that string:
if ("0123456789+-*/".indexOf(currentChar) >= 0) {
... // Good character
}
Another solution would be making a regex that allows only your characters to be specified, like this:
if (expr.replaceAll("[0-9+/*-]*", "").length() == 0) {
... // Expr contains only valid characters
}
Why don't you declare
String[] operatorsAndOperands = {"1","2","3","4","5","6","7","8","9","0","+","-","*","/"};
as a String, instead of an array of String. Then you can just use the contains method to check the characters against the valid operators.
Declare: char[] operatorsAndOperands; instead of: String[] operatorsAndOperands.
Or add this: String.valueOf(charToCompare) as the "contains" argument.
As has been pointed out, the issue is that you're checking for a char in a list of String objects, so you'll never find it.
You can make this check easier, though, by using a regular expression:
Pattern operatorsAndOperands = Pattern.compile("[0-9+\\-*/]");
Let's say I have this string: "abcd123fx".
Now, I want to make a method which checks (in order) if "a","b","c","d" etc is a number and if not, returns false. I don't know how to handle the n-th position of char and for each char, in order.
You can check if a character is a letter of number with teh Character class.
String text = ...
char ch = texct.charAt(nth);
if (Character.isLetter(ch)) {
// is a letter
} else if (Character.isDigit(ch)) {
// is a digit
}
Note: these method support characters in different blocks of the unicode. e.g. it will accept characters in Arabic or Korean.
Check the documentation. You can use charAt function.
if (Character.isLetter(yourString.charAt(index)))
// ... Letter
if (Character.isDigit(yourString.charAt(index)))
// ... Number
Check this page
Well there are a few ways you could do this. The simplest would probably be something along the lines of:
Character.isDigit(someString.charAt(x))
or a regex way would be someString.substring(x,x).matches("[0-9]")
To get the nth character of a string you should use charAt, the you should use the Charachter's isLetterOrDigit.
Usually, when you face these problems, you should search the javadoc looking for suitable methods.
Check out the Java tutorials on oracle.com for more information.
Specifically for this subject:
Characters, specifically the Character.isLetter(char ch) and Character.isDigit(char ch) methods
Strings and Manipulating Characters in a String, the simplest method is String.charAt(int index)
- As you have said that you are a newbie, i won't make this complicated using Regex, but will use inbuilt Java functionalities to answer this.
- First use subString() method to get the "abcd" part of the String, then use toCharArray() method to break the String into char elements, then use Character class's isDigit() method to know whether its a digit or not.
Eg:
public class T1 {
public static void main(String[] args){
String s = "abcd123fx";
String str = s.substring(0,4);
System.out.println(str);
char[] cArr = str.toCharArray();
for(char a :cArr){
if(Character.isDigit(a)){
System.out.println(a+" is a digit");
}else{
System.out.println(a+" is not a digit");
}
}
}
}
This might help you
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(.\\d+)?");
}
public static void main(String[] args){
System.out.println(isNumeric("abcd123fx"));
}
If you have a numeric string it will return true else false
public static void main(String[] args){
System.out.println(checkNumber("123a44"));
}
public static boolean checkNumber(String s){
for(int i = 0; i < s.length(); i++){
if(Character.isDigit(s.charAt(i))){
continue;
}
else{
return false;
}
}
return true;
}
You can also have a look into the ASCII table
Depending on this you can write a method:
private boolean isNumber(char a) {
int i = a;
if(i >= 48 && i <=57)
return true;
else
return false;
}
// now you can look by a String
private void checkString() {
String x = "abcd123fx ";
for(char counter : x.toCharArray())
System.out.println(isNumber(counter));
}