I am trying for find the Java code which:
1) Checks whether the String contains any consecutive integers
2) If it contains consecutive integers, then concatenate them i.e. my current message has integers separated by space only, so I need a way to concatenate those space separate integers. Eg:
message1 = "My no is 9543 21 00 10"
desired output = "My no is 9543210010"
message2 = "You can reach 2 me at 42315 468"
desired output = "You can reach 2 me at 42315468"
My main problem is to solve the above issue for phone numbers ie to concatenate space separated phone numbers together, so if someone has a different approach to solve this, please let me know.
I tried the following code but it doesn't work when string ends with a space:
if(message.matches(".*\\d.*")){
for (int i = 0; i <= message.length() -2 ; ++i){
if ((Character.isDigit(message.charAt(i))) && message.charAt(i+1) == ' ' && (Character.isDigit(message.charAt(i+2)))) {
StringBuilder sb = new StringBuilder(message);
sb.deleteCharAt(i+1);
message = sb.toString();
}
}
}
A community wiki answer based on peshmo's comment.
In other words, you are trying to remove spaces which are surrounded by digits.
message = message.replaceAll("(?<=\\d)\\s+(?=\\d)","");
This regex expression will do that. Try it here: https://regex101.com/r/qR33XN/1
This is untested code, just written in notepad but I think you will get the gist.
Basicly, split the string into an array with delimiter of a space(' '), glue everything back together. Add a space if index + 1 isn't a number otherwise don't add a space.
I hope this helps
String msg = "abc 1 2 3 333 yoo"
String[] splitted = msg.Split(' ');
String output = "";
for(int i = 0; i < splitted.Length - 1; i++) {
output += splitted[i];
if(i + 1 < splitted.Length - 1) {
if(isInteger(splitted[i]) && isInteger(splitted[i+1]))
continue;
}
output += " "
}
output = output.Trim();
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
Related
Java program to accept a string and count total numeric values.
public class Test2{
public static void main(String[] args){
String str = "I was 2 years old in 2002";
int count = 0, i;
for(i = 0; i < str.length(); i++){
if(str.charAt(i) >= 48 && str.charAt(i) <= 57){
count++;
// while(str.charAt(i) >= 48 && str.charAt(i) <= 57)
// i++;
}
}
System.out.println("Output: " +count);
}
}
Output = 5
After uncommenting the two lines written inside while loop -
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 25
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:712)
at Test2.main(Test2.java:9)
The output should be 2, because there are two numeric values - 2 and 2002
I have commented on the two lines in the above code, after uncommenting the code, the same logic works perfectly in C++.
An alternative to #DarkMatter´s answer using Pattern:
public static void main(String[] args) {
String str = "I was 2 years old in 2002";
long count = Pattern.compile("\\d+").matcher(str).results().count();
System.out.println(count);
}
You are checking individual charters so it counts every digit (as you probably realize). Java String has some nice tools to help you here. You could split the line into words and check each against a regular expression using String.matches():
String str = "I was 2 years old in 2002";
int count = 0;
for(String s : str.split(" ")) {
if(s.matches("[0-9]*")) {
count++;
}
}
System.out.println(count);
You can do the same thing (almost) with a stream:
String str = "I was 2 years old in 2002";
long count = Arrays.stream(str.split(" "))
.filter(s -> s.matches("[0-9]*")).count();
System.out.println(count);
In C, strings end in an ASCII NUL character (well, in basic C, strings don't exist, it's a library bolt-on, but most bolt-ons have NUL terminated strings). In java, that's not how it works.
The reason that your code is not working in java, but it is in C, is that you just keep going until you hit a non-digit character in that inner while loop. That means if the string ends in a digit (which yours does), your code asks the string: Give me the character at (one position beyond its length). In C that works; that's ASCII NUL, and thus your inner loop ends, as that's not a digit.
In java it doesn't, because you can't ask for a character beyond the end of a string.
You can 'fix' your code as pasted by also adding a check that i is still below length: if (i < str.length() && str.charAt(i).... ).
As the other answers showed you, there are more java idiomatic ways to solve this problem too, and probably the strategies shown in the other answers is what your average java coder would most likely do if faced with this problem. But there's nothing particularly wrong with your C-esque solution, once you add the 'check length' fix.
below code will input String from user and return the number of occurrences of numeric values as count.
import java.util.Scanner;
public class NumberCountingString
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str = in.nextLine();
int count = 0, i;
int size = str.length(); // will only get size once instead of using in loop which will always get size before comparing
for(i = 0; i < size; i++)
{
if(Character.isDigit(str.charAt(i))) //if char is digit count++
{
count++;
for (int j = i; j < size; ) //inner loop to check if next characters are also digits
{
if(Character.isDigit(str.charAt(j))) // if yes skip next char
{
i++;
j=i;
}
else{ //break inner loop
break;
}
}
}
}
System.out.println("Output: " +count);
}
}
There are many options in Java as already shared by others. Below is very similar to your existing code and gives your desired output:
public static void main(String[] args) {
String str = "I was 2 years old in 2002";
String[] splittedString = str.split(" ");
int count = 0, i;
for (i = 0; i < splittedString.length; i++) {
if (StringUtils.isNumeric(splittedString[i])) {
count++;
}
}
System.out.println("Output: " + count);
}
You can split this string into an array of words, then filter those words where codePoints of the characters match digits, i. e. allMatch (Character::isDigit), and count these words:
String str = "I was 2 years old in 2002";
long count = Arrays
// split string into an array of words
.stream(str.split("\\s+"))
// for each word check the code points of the
// characters, whether they are digits or not.
.filter(w -> w.codePoints()
.mapToObj(ch -> (char) ch)
.allMatch(Character::isDigit))
.count();
System.out.println(count); // 2
See also: Transform String to byte then to int
I am stuck in problem and not find
Solution please help me to resolve it . Below is code
String number = "000097127073653";
Boolean isOtherDigitFound = false;
int i=0;
for(int x=0 ; x<nunber.toCharArray() ; x++){
if(number.toChatArray()[x] != 0 && !isOtherDigitFound ){
isOtherDigitFound=true;
i=x;
}
}
number = number.subStr(x,number.length);
System.out.print(number);
I got the output that i wants which is 97127073653
But there is some easy way to do this .
I want to remove all occurence of 0 from Starting of string.but not from middle or somewhere else.
Example:-
I have Number like 0000123400022 then output should be like 123400022
Please help me
Thanks in advance 😊
For example, the above code to work may look like this
String number = "0000123400022";
Boolean isOtherDigitFound = false;
int i = 0;
for (int x = 0; x < number.length(); x++) {
if (number.charAt(x) != '0' && !isOtherDigitFound) {
isOtherDigitFound = true;
i = x;
break;
}
}
number = number.substring(i, number.length());
System.out.print(number);
You could use replaceAll method in Java's String class.
number = number.replaceAll("^0+", ""));
by adding ^ in replaceAll method replaces the leading characther and by adding $ the trailing characters are replaced. So if you want to replace the trailing 0 values of the string you can do number.replaceAll("0+$", "");
Now you may rewrite your code to simply three lines
String number = "000097127073653";
number = number.replaceAll("^0+", ""));
System.out.print(number);
I'll do it something like this. Hope it's easy enough to understand.
public String removingLeadingZero(final String number) {
if (StringUtils.isEmpty(number)) {
return number;
}
int i = 0;
while (number.charAt(i) == '0') { // Here'0' can be replaced with any charater you want
i++;
}
return number.substring(i);
}
If your strings are regular numbers (not containing any chars or non-numerical values), you could just cast your string to long and back. This will automatically remove all starting zeros.
String frontTrimmed = Long.parseLong(stringValue, 10) + "";
for example I have String: 61109010140000071219812874 and I want to apply algorithm, which will transofmation String in the following way:
611 09-010-14-000-00-712-19-812-87-4
as you can see, the point is to select the first three letters of the String, then add a white space, then add two dashes after two characters, then three, then again two characters. Something like:
### ##-###-##-###-##-###-##-###
Only I would like my algorithm to be universal. For example, for a string 6110901 output is: 611 09-01, for a string 61109010, output is: 611 09-010
I tried to use StringBuilder and the addCharAt method, but unfortunately it overwrites my string.
The above answers in the comments work but if you want a regular loop that builds what you want, this should do the trick:
public static void main(String args[]) {
String str = "61109010140000071219812874";
String output = "";
int segment = 2;
for(int i = 0; i < str.length(); i += segment){
segment = segment == 3 ? 2 : 3;
String seg = str.substring(i, Math.min(i + segment, str.length()));
char next = i == 0 ? ' ' : '-';
seg += next;
output += seg;
}
output = output.substring(0, output.length() - 1);
System.out.println(output); //611 09-010-14-000-00-712-19-812-87-4
}
Hi guys I am busy with breaking / splitting Strings.
However the String is not fixed so when the input changes the program still has to work with any character input.
Till now I got this far but I got lost.
I have made an array of characters and set the size of the array equal to the lenght of any string that is will get as input. I made a for loop to loop through the characters of a string.
how do I insert my string now into the array because I know that my string is not yet in there? Then when its finally looping through the characters of my string is has to printout numbers and operands on different lines. So the ouput would look like in this case like this;
1
+
3
,
432
.
123
etc
I want to do this without using matchers,scanner, etc. I want to use basic Java techniques like you learn in the first 3 chapters of HeadfirstJava.
public class CharAtExample {
public static void main(String[] args) {
// This is the string we are going to break down
String inputString = "1+3,432.123*4535-24.4";
int stringLength = inputString.length();
char[] destArray = new char[stringLength];{
for (int i=0; i<stringLength; i++);
}
You could use Character.isDigit(char) to distinguish numeric and not numeric chars as actually this is the single criteria to group multiple chars in a same line.
It would give :
public static void main(String[] args) {
String inputString = "1+3,432.123*4535-24.4";
String currentSequence = "";
for (int i = 0; i < inputString.length(); i++) {
char currentChar = inputString.charAt(i);
if (Character.isDigit(currentChar)) {
currentSequence += currentChar;
continue;
}
System.out.println(currentSequence);
System.out.println(currentChar);
currentSequence = "";
}
// print the current sequence that is a number if not printed yet
if (!currentSequence.equals("")) {
System.out.println(currentSequence);
}
}
Character.isDigit() relies on unicode category.
You could code it yourself such as :
if (Character.getType(currentChar) == Character.DECIMAL_DIGIT_NUMBER) {...}
Or you could code it still at a lower level by checking that the int value of the char is included in the range of ASCII decimal values for numbers:
if(currentChar >= 48 && currentChar <= 57 ) {
It outputs what you want :
1
+
3
,
432
.
123
*
4535
-
24
.
4
It's easier than you might think.
First: to get an array with the chars of your string you just use the toCharArray() method that all strings have. ex. myString.toCharArray()
Second: When you see that a character is not a number, you want to move to the next line, print the character and then move to the next line again. The following code does exactly that :
public class JavaApplication255 {
public static void main(String[] args) {
String inputString = "1+3,432.123*4535-24.4";
char[] destArray = inputString.toCharArray();
for (int i = 0 ; i < destArray.length ; i++){
char c = destArray[i];
if (isBreakCharacter(c)){
System.out.println("\n" + c);
} else {
System.out.print(c);
}
}
}
public static boolean isBreakCharacter(char c){
return c == '+' || c == '*' || c == '-' || c == '.' || c == ',' ;
}
char[] charArray = inputString.toCharArray();
Here is a possible solution where we go character by character and either add to an existing string which will be our numbers or it adds the string to the array, clears the current number and then adds the special characters. Finally we loop through the array as many times as we find a number or non-number character. I used the ASCII table to identify a character as a digit, the table will come in handy throughout your programming career. Lastly I changed the array to a String array because a character can't hold a number like "432", only '4' or '3' or '2'.
String inputString = "1+3,432.123*4535-24.4";
int stringLength = inputString.length();
String[] destArray = new String[stringLength];
int destArrayCount = 0;
String currentString = "";
for (int i=0; i<stringLength; i++)
{
//check it's ascii value if its between 0 (48) and 9 (57)
if(inputString.charAt(i) >= 48 && inputString.charAt(i) <= 57 )
{
currentString += inputString.charAt(i);
}
else
{
destArray[destArrayCount++] = currentString;
currentString = "";
//we know we don't have a number at i so its a non-number character, add it
destArray[destArrayCount++] = "" + inputString.charAt(i);
}
}
//add the last remaining number
destArray[destArrayCount++] = currentString;
for(int i = 0; i < destArrayCount; i++)
{
System.out.println("(" + i + "): " + destArray[i]);
}
IMPORTANT - This algorithm will fail if a certain type of String is used. Can you find a String where this algorithm fails? What can you do to to ensure the count is always correct and not sometimes 1 greater than the actual count?
I am going through the Java CodeBat exercises. Here is the one I am stuck on:
Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone, so "zipXzap" yields "zpXzp".
Here is my code:
public String zipZap(String str){
String s = ""; //Initialising return string
String diff = " " + str + " "; //Ensuring no out of bounds exceptions occur
for (int i = 1; i < diff.length()-1; i++) {
if (diff.charAt(i-1) != 'z' &&
diff.charAt(i+1) != 'p') {
s += diff.charAt(i);
}
}
return s;
}
This is successful for a few of them but not for others. It seems like the && operator is acting like a || for some of the example strings; that is to say, many of the characters I want to keep are not being kept. I'm not sure how I would go about fixing it.
A nudge in the right direction if you please! I just need a hint!
Actually it is the other way around. You should do:
if (diff.charAt(i-1) != 'z' || diff.charAt(i+1) != 'p') {
s += diff.charAt(i);
}
Which is equivalent to:
if (!(diff.charAt(i-1) == 'z' && diff.charAt(i+1) == 'p')) {
s += diff.charAt(i);
}
This sounds like the perfect use of a regular expression.
The regex "z.p" will match any three letter token starting with a z, having any character in the middle, and ending in p. If you require it to be a letter you could use "z[a-zA-Z]p" instead.
So you end up with
public String zipZap(String str) {
return str.replaceAll("z[a-zA-Z]p", "zp");
}
This passes all the tests, by the way.
You could make the argument that this question is about raw string manipulation, but I would argue that that makes this an even better lesson: applying regexes appropriately is a massively useful skill to have!
public String zipZap(String str) {
//If bigger than 3, because obviously without 3 variables we just return the string.
if (str.length() >= 3)
{
//Create a variable to return at the end.
String ret = "";
//This is a cheat I worked on to get the ending to work easier.
//I noticed that it wouldn't add at the end, so I fixed it using this cheat.
int minusAmt = 2;
//The minus amount starts with 2, but can be changed to 0 when there is no instance of z-p.
for (int i = 0; i < str.length() - minusAmt; i++)
{
//I thought this was a genius solution, so I suprised myself.
if (str.charAt(i) == 'z' && str.charAt(i+2) == 'p')
{
//Add "zp" to the return string
ret = ret + "zp";
//As long as z-p occurs, we keep the minus amount at 2.
minusAmt = 2;
//Increment to skip over z-p.
i += 2;
}
//If it isn't z-p, we do this.
else
{
//Add the character
ret = ret + str.charAt(i);
//Make the minus amount 0, so that we can get the rest of the chars.
minusAmt = 0;
}
}
//return the string.
return ret;
}
//If it was less than 3 chars, we return the string.
else
{
return str;
}
}