Removing leading zero in java code - java

May I know how can I remove the leading zero in JAVA code? I tried several methods like regex tools
"s.replaceFirst("^0+(?!$)", "") / replaceAll("^0*", "");`
but it's seem like not support with my current compiler compliance level (1.3), will have a red line stated the method replaceFirst(String,String)is undefined for the type String.
Part of My Java code
public String proc_MODEL(Element recElement)
{
String SEAT = "";
try
{
SEAT = setNullToString(recElement.getChildText("SEAT")); // xml value =0000500
if (SEAT.length()>0)
{
SEAT = SEAT.replaceFirst("^0*", ""); //I need to remove leading zero to only 500
}
catch (Exception e)
{
e.printStackTrace();
return "501 Exception in proc_MODEL";
}
}
}
Appreciate for help.

If you want remove leading zeros, you could parse to an Integer and convert back to a String with one line like
String seat = "001";// setNullToString(recElement.getChildText("SEAT"));
seat = Integer.valueOf(seat).toString();
System.out.println(seat);
Output is
1
Of course if you intend to use the value it's probably better to keep the int
int s = Integer.parseInt(seat);
System.out.println(s);

replaceFirst() was introduced in 1.4 and your compiler pre-dates that.
One possibility is to use something like:
public class testprog {
public static void main(String[] args) {
String s = "0001000";
while ((s.length() > 1) && (s.charAt(0) == '0'))
s = s.substring(1);
System.out.println(s);
}
}
It's not the most efficient code in the world but it'll get the job done.
A more efficient segment without unnecessary string creation could be:
public class testprog {
public static void main(String[] args) {
String s = "0001000";
int pos = 0;
int len = s.length();
while ((pos < len-1) && (s.charAt(pos) == '0'))
pos++;
s = s.substring(pos);
System.out.println(s);
}
}
Both of those also handle the degenerate cases of an empty string and a string containing only 0 characters.

Using a java method str.replaceAll("^0+(?!$)", "") would be simple;
First parameter:regex -- the regular expression to which this string is to be matched.
Second parameter: replacement -- the string which would replace matched expression.

As stated in Java documentation, 'replaceFirst' only started existing since Java 1.4 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceFirst(java.lang.String,%20java.lang.String)
Use this function instead:
String removeLeadingZeros(String str) {
while (str.indexOf("0")==0)
str = str.substring(1);
return str;
}

Related

Check if any part of a string input is not a number

I couldnt find an answer for this in Java, so I'll ask here. I need to check if 3 parts of a string input contains a number (int).
The input will be HOURS:MINUTES:SECONDS (E.g. 10:40:50, which will be 10 hours, 40 minutes and 50 seconds). So far I am getting the values in String[] into an array by splitting it on :. I have parsed the strings into ints and I am using an if statement to check if all 3 parts is equal or larger than 0. The problem is that if I now use letters I will only just get an error, but I want to check if any of the 3 parts contains a character that is not 0-9, but dont know how.
First I thought something like this could work, but really dont.
String[] inputString = input.split(":");
if(inputString.length == 3) {
String[] alphabet = {"a","b","c"};
if(ArrayUtils.contains(alphabet,input)){
gives error message
}
int hoursInt = Integer.parseInt(inputString[0]);
int minutesInt = Integer.parseInt(inputString[1]);
int secondsInt = Integer.parseInt(inputString[2]);
else if(hoursInt >= 0 || minutesInt >= 0 || secondsInt >= 0) {
successfull
}
else {
gives error message
}
else {
gives error message
}
In the end I just want to check if any of the three parts contains a character, and if it doesnt, run something.
If you are sure you always have to parse a String of the form/pattern HH:mm:ss
(describing a time of day),
you can try to parse it to a LocalTime, which will only work if the parts HH, mm and ss are actually valid integers and valid time values.
Do it like this and maybe catch an Exception for a wrong input String:
public static void main(String[] arguments) {
String input = "10:40:50";
String wrongInput = "ab:cd:ef";
LocalTime time = LocalTime.parse(input);
System.out.println(time.format(DateTimeFormatter.ISO_LOCAL_TIME));
try {
LocalTime t = LocalTime.parse(wrongInput);
} catch (DateTimeParseException dtpE) {
System.err.println("Input not parseable...");
dtpE.printStackTrace();
}
}
The output of this minimal example is
10:40:50
Input not parseable...
java.time.format.DateTimeParseException: Text 'ab:cd:ef' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalTime.parse(LocalTime.java:441)
at java.time.LocalTime.parse(LocalTime.java:426)
at de.os.prodefacto.StackoverflowDemo.main(StackoverflowDemo.java:120)
I would personally create my own helper methods for this, instead of using an external library such as Apache (unless you already plan on using the library elsewhere in the project).
Here is an example of what it could look like:
public static void main(String[] arguments) {
String time = "10:50:45";
String [] arr = time.split(":");
if (containsNumbers(arr)) {
System.out.println("Time contained a number!");
}
//You can put an else if you want something to happen when it is not a number
}
private static boolean containsNumbers(String[] arr) {
for (String s : arr) {
if (!isNumeric(s)) {
return false;
}
}
return true;
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(.\\d+)?");
}
containsNumbers will take a String array as an input and use an enhanced for loop to iterate through all the String values, using the other helper method isNumeric that checks if the String is a number or not using regex.
This code has the benefit of not being dependent on Exceptions to handle any of the logic.
You can also modify this code to use a String as a parameter instead of an array, and let it handle the split inside of the method instead of outside.
Note that typically there are better ways to work with date and time, but I thought I would answer your literal question.
Example Runs:
String time = "sd:fe:gbdf";
returns false
String time = "as:12:sda";
returns false
String time = "10:50:45";
returns true
You can check the stream of characters.
If the filter does not detect a non-digit, return "Numeric"
Otherwise, return "Not Numeric"
String str = "922029202s9202920290220";
String result = str.chars()
.filter(c -> !Character.isDigit(c))
.findFirst().isEmpty() ? "Numeric"
: "Not Numeric";
System.out.println(result);
If you want to check with nested loop you can see this proposal:
Scanner scanner = new Scanner(System.in);
String [] inputString = scanner.nextLine().split(":");
for (int i = 0; i < inputString.length; i++) {
String current = inputString[i];
for (int k = 0; k < current.length(); k++) {
if (!Character.isDigit(current.charAt(k))) {
System.out.println("Error");
break;
}
}
}
you could use String.matches method :
String notANum= "ok";
String aNum= "7";
if(notANum.matches("^[0-9]+$") sop("no way!");
if(aNum.matches("^[0-9]+$") sop("yes of course!");
The code above would print :
yes of course
The method accepts a regex, the one in the above exemple is for integers.
EDIT
I would use this instead :
if(input.matches("^\d+:\d+:\d+$")) success;
else error
You don't have to split the string.
I tried to make your code better, take a look. You can use Java regex to validate numbers. also defined range for time so no 24:61:61 values is allowed.
public class Regex {
static boolean range(int timeval,int min,int max)
{
boolean status=false;
if(timeval>=min && timeval<max)
{status=true;}
return status;
}
public static void main(String[] args) {
String regex = "[0-9]{1,2}";
String input ="23:59:59";
String msg="please enter valid time ";
String[] inputString = input.split(":");
if(inputString[0].matches(regex) && inputString[1].matches(regex) && inputString[2].matches(regex) )
{
if(Regex.range(Integer.parseInt(inputString[0]), 00, 24) &&Regex.range(Integer.parseInt(inputString[1]), 00, 60) && Regex.range(Integer.parseInt(inputString[2]), 00, 60))
{msg="converted time = " + Integer.parseInt(inputString[0]) + " : " +Integer.parseInt(inputString[1])+ " : " +Integer.parseInt(inputString[2]) ;}
}
System.out.println(msg);
}
}

How to correctly write a C# helper class to read multiple integers from single line?

I'm trying to switch from Java to C# and am also practicing competitive programming problems, but what I found that C# doesn't have a convenient way to read a single int from the console like Scanner.nextInt(). Now to be fair I don't use that approach in Java either, but a helper class instead that does something like this:
(This is a static inner class):
static class InputReader {
public String[] input;
public BufferedReader reader;
ublic int current;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
input = null;
current = 0;
}
public String next() {
while (input == null || current == input.length) {
try {
current = 0;
input = reader.readLine().split("\\s");
} catch (IOException e) {
throw new RuntimeException();
}
}
return input[current++];
}
public int nextInt() {
return Integer.parseInt(next());
}
}
I tried rewriting the same in C# and it came out like this:
internal static class InputHelper
{
private static int current;
private static string[] buffer;
public static string next()
{
while (buffer == null || current == buffer.Length)
{
current = 0;
buffer = Console.ReadLine()?.Split();
}
return buffer[current++];
}
public static int NextInt()
{
return int.Parse(next());
}
}
However when I pasted in this sequence from a problem statement, I got an exception (NumberFormatException):
3
5 1
3
3 3
1 2 3
4 1
1
EDIT: My suspicion is that it throws an exception because of the different line breaks used on windows linux, but this could be totally wrong.
And other times for example:
var n = InputHelper.NextInt();
while (n > 0)
{
n--;
Console.WriteLine(InputHelper.NextInt());
}
It works just fine. Any ideas as to why it could be wrong?
I don't know why yours doesn't work, but you could try this instead:
public static class ConsoleHelper
{
private static string[] input = new string[0];
private static int inputIndex;
public static void ReadNextInput()
{
input = Console.ReadLine().Split();
inputIndex = 0;
}
public static int GetNextInt()
{
return int.Parse(ReadNextWord());
}
public static string GetNextWord()
{
return ReadNextWord();
}
private static string ReadNextWord()
{
if (inputIndex >= input.Length)
{
ReadNextInput();
}
return input[inputIndex++];
}
}
I've been using this in competitions, and up till now, have never failed me.
EDIT:
You could try this split: Split(' ', StringSplitOptions.RemoveEmptyEntries);
This automatically removes empty elements in the output array.
However when I pasted in this sequence from a problem statement, I got an exception (NumberFormatException).
I suspect this is because of trailing spaces on the input. By default, Split will emit an empty entry when it encounters a delimiter that isn't followed by a non-delimiter.
For example, given the input 1 2 (with two spaces), the result would be ["1", "", "2"] because the first space is followed by another delimiter. Similarly, the input 1 2 (with a trailing space) would yield ["1", "2", ""], because the final delimiter has nothing to its right.
This is often a point of confusion, and the documentation for Split doesn't do a great job of informing you:
Returns: An array whose elements contain the substrings in this instance that are delimited by one or more characters in separator. [emphasis mine]
To me, that phrasing implies that contiguous delimiters would be 'flattened' into one, but that's not how it works at all.
To avoid this behavior, use an overload of String.Split that accepts StringSplitOptions, and specify StringSplitOptions.RemoveEmptyEntries.

Removing special character without using Java Matcher and Pattern API

I am trying to write one java program. This program take a string from the user as an input and display the output by removing the special characters in it. And display the each strings in new line
Let's say I have this string Abc#xyz,2016!horrible_just?kidding after reading this string my program should display the output by removing the special characters like
Abc
xyz
2016
horrible
just
kidding
Now I know there are already API available like Matcher and Patterns API in java to do this. But I don't want to use the API since I am a beginner to java so I am just trying to crack the code bit by bit.
This is what I have tried so far. What I have done here is I am taking the string from the user and stored the special characters in an array and doing the comparison till it get the special character. And also storing the new character in StringBuilder class.
Here is my code
import java.util.*;
class StringTokens{
public void display(String string){
StringBuilder stringToken = new StringBuilder();
stringToken.setLength(0);
char[] str = {' ','!',',','?','.','_','#'};
for(int i=0;i<string.length();i++){
for(int j =0;j<str.length;j++){
if((int)string.charAt(i)!=(int)str[j]){
stringToken.append(str[j]);
}
else {
System.out.println(stringToken.toString());
stringToken.setLength(0);
}
}
}
}
public static void main(String[] args){
if(args.length!=1)
System.out.println("Enter only one line string");
else{
StringTokens st = new StringTokens();
st.display(args[0]);
}
}
}
When I run this code I am only getting the special characters, I am not getting the each strings in new line.
One easy way - use a set to hold all invalid characters:
Set<Character> invalidChars = new HashSet<>(Arrays.asList('$', ...));
Then your check boils down to:
if(invaidChars.contains(string.charAt(i)) {
... invalid char
} else {
valid char
}
But of course, that still means: you are re-inventing the wheel. And one does only re-invent the wheel, if one has very good reasons to. One valid reason would be: your assignment is to implement your own solution.
But otherwise: just read about replaceAll. That method does exactly what your current code; and my solution would be doing. But in a straight forward way; that every good java programmer will be able to understand!
So, to match your question: yes, you can implement this yourself. But the next step is to figure the "canonical" solution to the problem. When you learn Java, then you also have to focus on learning how to do things "like everybody else", with least amount of code to solve the problem. That is one of the core beauties of Java: for 99% of all problems, there is already a straight-forward, high-performance, everybody-will-understand solution out there; most often directly in the Java standard libraries themselves! And knowing Java means to know and understand those solutions.
Every C coder can put down 150 lines of low-level array iterating code in Java, too. The true virtue is to know the ways of doing the same thing with 5 or 10 lines!
I can't comment because I don't have the reputation required. Currently you are appending str[j] which represents special character. Instead you should be appending string.charAt(i). Hope that helps.
stringToken.append(str[j]);
should be
stringToken.append(string.charAt(i));
Here is corrected version of your code, but there are better solutions for this problem.
public class StringTokens {
static String specialChars = new String(new char[]{' ', '!', ',', '?', '.', '_', '#'});
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Enter only one line string");
} else {
display(args[0]);
}
}
public static void display(String string) {
StringBuilder stringToken = new StringBuilder();
stringToken.setLength(0);
for(char c : string.toCharArray()) {
if(!specialChars.contains(String.valueOf(c))) {
stringToken.append(c);
} else {
stringToken.append('\n');
}
}
System.out.println(stringToken);
}
}
public static void main(String[] args) {
String a=",!?#_."; //Add other special characters too
String test="Abc#xyz,2016!horrible_just?kidding"; //Make this as user input
for(char c : test.toCharArray()){
if(a.contains(c+""))
{
System.out.println(); //to avoid printing the special character and to print newline
}
else{
System.out.print(c);
}
}
}
you can run a simple loop and check ascii value of each character. If its something other than A-Z and a-z print newline skip the character and move on. Time complexity will be O(n) + no extra classes used.
String str = "Abc#xyz,2016!horrible_just?kidding";
char charArray[] = str.toCharArray();
boolean flag=true;;
for (int i = 0; i < charArray.length; i++) {
int temp2 = (int) charArray[i];
if (temp2 >= (int) 'A' && temp2 <= (int) 'Z') {
System.out.print(charArray[i]);
flag=true;
} else if (temp2 >= (int) 'a' && temp2 <= (int) 'z') {
System.out.print(charArray[i]);
flag=true;
} else {
if(flag){
System.out.println("");
flag=false;
}
}
}

java find if the string contains 2 other strings

I have 2 strings "test" "bet" and another string a="tbtetse". I need to check if the "tbtetse" contains the other two strings.
I was thinking if I could find all the anagrams of string a and and then find the other two strings in those, but it doesn't work that way and also my anagram code is failing for a lengthy string.
Could you please help with any other ways to solve it?
Assuming you're trying to test whether the letters in a can be used to form an anagram of the test strings test and bet: I recommend making a dictionary (HashMap or whatever) of character counts from string a, indexed by character. Build a similar dictionary for the words you're testing. Then make sure that a has at least as many instances of each character from the test strings as they have.
Edit: Alcanzar suggests arrays of length 26 for holding the counts (one slot for each letter). Assuming you're dealing with only English letters, that is probably less of a hassle than dictionaries. If you don't know the number of allowed characters, the dictionary route is necessary.
Check below code, it may help you.
public class StringTest {
public static void main(String[] args) {
String str1 = "test";
String str2 = "bev";
String str3 = "tbtetse";
System.out.println(isStringPresent(str1, str2, str3));
}
private static boolean isStringPresent(String str1, String str2, String str3) {
if ((str1.length() + str2.length()) != str3.length()) {
return false;
} else {
String[] str1Arr = str1.split("");
String[] str2Arr = str2.split("");
for (String string : str1Arr) {
if (!str3.contains(string)) {
return false;
}
}
for (String string : str2Arr) {
if (!str3.contains(string)) {
return false;
}
}
}
return true;
}
}
basically you need to count characters in both sets and compare them
void fillInCharCounts(String word,int[] counts) {
for (int i = 0; i<word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a';
counts[index]++;
}
}
int[] counts1 = new int[26];
int[] counts2 = new int[26];
fillInCharCounts("test",counts1);
fillInCharCounts("bet",counts1);
fillInCharCounts("tbtese",counts2);
boolean failed = false;
for (int i = 0; i<counts1.length; i++) {
if (counts1[i] > counts2[i]) {
failed = true;
}
}
if (failed) {
whatever
} else {
something else
}
If you are generalizing it, don't forget to call .toLowerCase() on the word before sending it in (or fix the counting method).
Pseudo code:
Make a copy of string "tbtetse".
Loop through each character in "test".
Do a indexOf() search for the character in your copied string and remove it if found.
If not found, fail.
Do the same for the string "bet".
class WordLetter {
char letter;
int nth; // Occurrence of that letter
...
}
One now can use Sets
Set<WordLetter>
// "test" = { t0 e0 s0 t1 }
Then testing reduces to set operations. If both words need to be present, a union can be tested. If both words must be formed from separate letters, a set of the concatenation can be tested.

Recursive removal of characters in Java

As an exercise, the code block below intends to recursively go through a string and remove all the of the "x" characters. It does that, but I would like to keep track of the newStr without passing it as a parameter in the method. Is there anyway to move it into the method body?
Thanks!
public static String deathToX(String str, String newStr) {
//look for x char
if(str.substring(0, 1).equals("x")) {
//do nothing
} else {
//add non-x char to newStr
newStr += str.charAt(0);
}
if(str.length() == 1) {
return newStr;
}
return deathToX(str.substring(1), newStr);
}
public static void main(String[] args) {
System.out.println("Return: " + deathToX("xnoxmore", ""));
}
Well, you could change the code to:
public static String deathToX(String str)
{
// Termination case
if (str.length() == 0)
{
return str;
}
// Work out whether or not we want the first character
String prefix = str.startsWith("x") ? "" : str.substring(0, 1);
// Let the recursive call handle the rest of the string, and return
// the prefix (empty string or the first character) followed by the
// x-stripped remainder.
return prefix + deathToX(str.substring(1));
}
Is that the sort of thing you were thinking of?
Of course, this is a horribly inefficient way of doing string manipulation, but I assume you're more interested in the recursive nature of things.
I would like to keep track of the newStr without passing it as a parameter in the method.
Why? Passing the intermediary result into the function is often required in functional-style recursive programming. What I do is make a function that handles the bulk of the work and accepts the accumulator, and make a wrapper function that calls the previous one with the required starter value:
private static String deathToX0(String str, String newStr) {
// the original implementation
}
public static String deathToX(String str) {
return deathToX(str, "");
}
As an aside, you might not want to use a String for the intermediate result because of the copying involved. A StringBuilder would be faster.
The short answer is yes... with recursion typically on the way down the tree you work out the bit at each level in this case blank or the current character. So the return statement should call itself recursively then at the bottom of the tree the answer you wanted is reconstructed by adding together the sections at each level.
public static String deathToX(String str){
if (!str.isEmpty()){
return (str.substring(0, 1).equals("x") ? "" : str.substring(0, 1)) + deathToX(str.substring(1));
}else{
return "";
}
}
public static void main(String[] args){
System.out.println("Return: " + deathToX("xnoxmore"));
}
In the sample above I used the shorthand if format to put it all on one line but you could expand it out. You should be able to see that the recursive function recurses on the return statement and I put in a special case for the last level. If you were to split it and put this levels answer in a local variable e.g. tmp then you would use:
return tmp + deathToX(str.substring(1));
Remember recursion means that the current execution is only paused until the lower ones finish so you can happily store info to recover on your way back up. Hope this helps :)
public class solution {
// Return the changed string
public static String removeX(String input){
if(input.equals("") || input.equals("x"))
return "";
String returnStr="";
removeX(input.substring(1));
for(int i=0;i<input.length();i++)
{
if(input.charAt(i)=='x')
continue;
else
returnStr+=input.charAt(i);
}
return returnStr;
}
}
This is my approach. This code goes to the end of the string, if it gets X as last string, it returns ""(nothing), then it checks the whole substring for "x", if its present in the string, it will continue, else it will append rest character to that string and it goes on.
Finally returns the updated string.!
Hope this helps..!! well, this is my first contribution here :)

Categories

Resources