Extracting numbers from a string while keeping spaces - java

Given a string, I want to extract the numbers and keep a spacing between them.
The procedure for this generally involves removing all spacing so that 12 3 becomes 123 which I'm avoiding.
For example if the input is 17/(2 + 3)-13 I want 17 2 3 13.
I also have methods that extract the operators and parenthesis in between them but I can't separate the numbers greater than 9.
Here's my attempt which produces out of bounds exceptions
public static void partition(){
String word = "123 -asdfqwerty- 45";
String kajigger = "";
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(Character.isDigit(c)){
int j = i;
while(Character.isDigit(word.charAt(j))){
kajigger += word.charAt(j);
j++;
}
}
}
System.out.println(kajigger);
}
In this example I wanted the output 123 45
The general idea is converting from infix to postfix by moving all numbers the the left and operators to the right.

You go by this way :
replace all multiple following (+) chars which are non-digits (\D) by a single space (" ")
so \D+ changes 7/(2 + 3)-13 into 7 2 3 13
String str = "17/(2 + 3)-13";
str = str.replaceAll("\\D+", " ");
System.out.println(str); // 17 2 3 13
Regex demo

Related

After Method: Cut String at '-' or ' '

The input string may contain hyphens and spaces that mark places to truncate the string. The output string will be a truncated version of the input string, and the input int value is the desired length of the output string. The output string should truncate the input string at the first legal spot so the output string will have the desired length. If the truncation happens at a space, the output does not include the space, but if the truncation happens at a hyphen, the output includes the hyphen. No other hyphens are included in the output, but the other spaces are.
How can I fix my code to get the "What code should output" output without using arrays and breaks?
public static String after(int length, String s1) {
StringBuilder sb = new StringBuilder();
int x = 0;
for(; sb.length() < length && x < s1.length() - 1; x = x + 1) {
if(s1.charAt(x) != '-') {
sb.append(s1.charAt(x));
}
}
for(; x < sb.length() && s1.charAt(x) - 1 != '-'; x = x + 1) {
sb.append(s1.charAt(x));
}
if(s1.charAt(x) == ' ' && s1.length() + 1 == s1.length()) {
sb.append(s1.charAt(x));
}
return sb.toString();
}
Input are:
HW2.after(5, "La-te-ly the-re.")
HW2.after(6, "La-te-ly the-re.")
HW2.after(7, "La-te-ly the-re.")
I am getting the output :
"Latel"
"Lately"
"Lately "
What Actually output is:
"Late-"
"Lately"
"Lately the-"
Sounds like a homework question, so I'll just give you the approach I used, so you can think through the coding for yourself...
Stop your first loop one short of the number of requested characters. You have to not skip spaces, but keep a count of them, and subtract that from sb.length() you're testing in your loop because your desired length excludes spaces.
Then deal with the case where you're now pointing to a space, by testing for that, and if true, adding it to the output string and advancing x.
Then keep looking at the next character and adding it to the result as long as it isn't a dash or a space.
Finally, if you stopped on a dash, add it to the output.

Sum the digits in a string

I wrote a program that sums the int values in a String. I'm getting the wrong output though. I can't quite figure out the issue. The expected output should be 23 and 29 but I am getting 263 and 269. Any suggestions would be helpful; it seems it is putting a 6 between my outputs for some reason.
public class ParseString
{
String str;
public ParseString(String x)
{
this.str = x;
}
public int sumOfAllDigits()
{
int total = 0;
char[] arr = new char[this.str.length()];
for(int i = 0; i < this.str.length(); i++)
{
arr[i] = this.str.charAt(i);
}
for(int i = 0; i < arr.length; i++)
{
if(arr[i] >= '0' && arr[i] <= '9')
{
total = total + arr[i];
}
}
return total;
}
public class TestParseString
{
public static void main(String[] args)
{
String s1 = "AB458JK2L#4";
ParseString ps1 = new ParseString(s1);
System.out.println("Sum of all digits in \"" + s1 + "\" is: ");
System.out.println(ps1.sumOfAllDigits());
System.out.println();
String s2 = "8927KL3PY";
ParseString ps2 = new ParseString(s2);
System.out.println("Sum of all digits in \"" + s2 + "\" is: ");
System.out.println(ps2.sumOfAllDigits());
}
}
It's not that a 6 is inserted into your sum; it's that your sum is 240 too high. There are 5 digits in each of your test strings. What is missing here is what goes on in the conversion between char and int. A '0' is not 0; when a char is widened to an int for summing, it takes the ASCII value, which for numbers is the represented number plus 48. E.g. '0' -> 48, '1' -> 49, etc.
An extra 48 added 5 times yields an extra 240.
Because the digits are coded in order starting with '0' at 48, you can subtract '0' to take away the unwanted 48.
total = total + arr[i] - '0';
As an aside, as already mentioned in the comments on the question, toCharArray() gets you the char[] for a String more easily than manually copying each character.
The problem lies here:
total = total + arr[i];
arr[i] is a char. When you use the + operator on it, with the other operand being an int, you are actually adding the ASCII value of the character, which is 48 to 57 for 0 to 9.
You think you are doing this:
4 + 5 + 8 + 2 + 4
But actually the program is doing:
52 + 53 + 56 + 50 + 52
So that's why you get such a large number.
You need to parse the characters to get the correct output. One way to do this is to just subtract 48!
total = total + (arr[i] - 48);
Or you can convert it to a string first, then parse it as an int:
total = total + Integer.parseInt(Character.toString(arr[i]));

How to write a program that returns number of occurrences of a string in another string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So I'm new to programming. I'm using java. Right now I have an assignment I can't solve on a website that teaches java.
This is the assignment
Write a program that returns number of occurrences of a string in another string.
E.g
Input:
First String: the
Second String: The students are working hard in the faculty of Engineering because they love it
Output:
3
Note: You should only use nested loops. Don’t use methods like indexOf or substring.
Ienter image description here reached to the code the calculate the number of occurrences but it failed in case of repeated letters
E.g
input:
First String : ooo
Second String : wooooooooooooooooooooow
Output : 21
It's supposed to be 7 since the ooo have only repeated 7 times
This question can be simply solved by using z-function in linear time.
int NumberOfcopies(String t, String h){
// t = the first string i.e "ooo"
// h = the second string i.e "wooooooooooooooooooooow"
String s = t + "$" + h; // adding a sentinel character in between
int n = s.length(); // length of new string
int[] z = new int[n]; // z array
// Code ref : http://e-maxx-eng.github.io/string/z-function.html
int l = 0, r = 0;
for (int i = 1; i < n; i++){
if (i <= r)
z[i] = Math.min(r - i + 1, z[i - 1]);
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
++z[i];
if (i + z[i] - 1 > r){
l = i;
r = i + z[i] - 1;
}
}
//checking for all the occurance of string t in string h
int res = 0;
for (int i = t.length() + 1; i < n; ){
if (z[i] == t.length()){
//A copy is found so skip next t.length chars
i += t.length();
++res;
}
else ++i;
}
System.out.println("Number of Occurance : " + res);
return res;
}
The Z-function for this string is an array of length n where
the i-th element is equal to the greatest number of characters
starting from the position i that coincide with the first
characters of s.
This can be exploited to find the number of occurrences of a string t in another string h. Suppose we join the string t and h with a sentinel character in between (Sentinel character is a character that does not occur in either of the strings) to form a new string s.
Lets us calculate the z function in array z[].
Now lets start searching from the character after the sentinel character i.e. the characters of string h. For i-th character in string h ( such that i-th character belongs to string s) if z[i] equals to length of string t (the pattern) then it implies that starting from i-th char, the t.length() chars are same as the first t.length() chars of string s which is what the string t equals.
example :
t = ab
h = aaabaab
s = a b $ a a a b a a b
z = 0 0 0 1 1 2 0 1 2 0
i = 0 1 2 3 4 5 6 7 8 9
for i = 5 we can see that z[i] == t.length(), that means we found a copy. Now to prevent Overlapping solutions, we skip the t.length() chars hence now i = 7
continuing this will get you the result.

java convert String of integers into possible combination of ASCII characters

Say that I have
String input = "Programming", result="\0";
int temp;
for (int i=0;i<input.length();++i) {
temp = input.charAt(i);
result += temp;
}
result would be 8011411110311497109109105110103. I know that
P = 80
r = 114
o = 111
g = 103
r = 114
a = 97
m = 109
m = 109
i = 105
n = 110
g = 103
Out of curiosity, is it possible, in easy way, to reverse the process?
what you would have to do is assume that Each number lies between either 'A' to 'Z', (65 to 90) or 'a' to 'z' (97 to 122)
get the first 2 digits via a call to substring()
check if those lie within the above bounds by converting to a numeric type
if they do then continue with the loop
else get the third digit and check that
it would be much simpler if you could have it be padded to three digits so you would know that every three digits formed an ASCII letter
code that works only if it is letters:
public static void main(String[] args) {
String toConvert= "8011411110311497109109105110103";
String result="";
while(toConvert.length()>0){
String digits=toConvert.substring(0, 2);
int num=Integer.valueOf(digits);
if(('A'<=num&&num<='Z')||('a'<=num&&num<='z')){
toConvert=toConvert.substring(2);
}
else{
digits=toConvert.substring(0, 3);
num=Integer.valueOf(digits);
toConvert=toConvert.substring(3);
}
String letter = String.valueOf((char) num);
result+=letter;
}
System.out.println(result);
}
note if you change the test to num>25 , then it will correctly work for all ASCII values from 26 up: for values 26 to 99, it will interpret them as having 2 digits correctly, for values from 100 to 255 it will only look at the first 2 digits, so they will be seen as 10-25, and will be interpreted as 3 digits long

Integer to two digits hex in Java

I need to change a integer value into 2-digit hex value in Java.Is there any way for this.
Thanks
My biggest number will be 63 and smallest will be 0.
I want a leading zero for small values.
String.format("%02X", value);
If you use X instead of x as suggested by aristar, then you don't need to use .toUpperCase().
Integer.toHexString(42);
Javadoc: http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#toHexString(int)
Note that this may give you more than 2 digits, however! (An Integer is 4 bytes, so you could potentially get back 8 characters.)
Here's a bit of a hack to get your padding, as long as you are absolutely sure that you're only dealing with single-byte values (255 or less):
Integer.toHexString(0x100 | 42).substring(1)
Many more (and better) solutions at Left padding integers (non-decimal format) with zeros in Java.
String.format("%02X", (0xFF & value));
Use Integer.toHexString(). Dont forget to pad with a leading zero if you only end up with one digit. If your integer is greater than 255 you'll get more than 2 digits.
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(myInt));
if (sb.length() < 2) {
sb.insert(0, '0'); // pad with leading zero if needed
}
String hex = sb.toString();
If you just need to print them try this:
for(int a = 0; a < 255; a++){
if( a % 16 == 0){
System.out.println();
}
System.out.printf("%02x ", a);
}
i use this to get a string representing the equivalent hex value of an integer separated by space for every byte
EX : hex val of 260 in 4 bytes = 00 00 01 04
public static String getHexValString(Integer val, int bytePercision){
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(val));
while(sb.length() < bytePercision*2){
sb.insert(0,'0');// pad with leading zero
}
int l = sb.length(); // total string length before spaces
int r = l/2; //num of rquired iterations
for (int i=1; i < r; i++){
int x = l-(2*i); //space postion
sb.insert(x, ' ');
}
return sb.toString().toUpperCase();
}
public static void main(String []args){
System.out.println("hex val of 260 in 4 bytes = " + getHexValString(260,4));
}
According to GabrielOshiro, If you want format integer to length 8, try this
String.format("0x%08X", 20) //print 0x00000014

Categories