How can I remove white spaces from an input? - java

This is the input: enter image description here
I want to get the last number but how? (1,2,6)
I tried this:
String line = scanner.nextLine();
String[] parts = line.split(" ");
int ProductCount =Integer.parseInt(parts[3].replaceAll(" ", ""));

If you want the last number you can do it like this.
.*? reluctantly grab the characters
(\\d+)$ - capture one or more digits at end of string.
$1 back reference to captured value (21 in this case)
and convert to an int.
String s = "kssk sk k22 s 21";
int v = Integer.parseInt(s.replaceAll(".*?(\\d+)$","$1"));
System.out.println(v);
prints
21
A somewhat better alternative might be to do the following if there is always a space before the last number.
get the last index of a white space
and starting with the next character, get the substring and convert to an integer.
int i = s.lastIndexOf(' '); // returns -1 if no space is found.
int v = Integer.parseInt(s.substring(i+1));

Related

Split a string contain hyphen and minus sign

This question is similar to my previous question Split a string contain dash and minus sign. But I asked it in a wrong and then it got a slightly different semantics and people answered(including) in that perspective. Therefore rather than modifying that question I thought it's better to ask in a new question.
I have to split a string which contain hyphen-minus character and minus sign. I tried to split based on the unicode character (https://en.wikipedia.org/wiki/Hyphen#Unicode), still it considering minus sign same as hyphen-minus character. Is there a way I can solve it?
Expected output
(coun)
(US)
-1
Actual output
(coun)
(US)
// actually blank line will print here but SO editor squeezing the blank line
1
public static void main(String[] args) {
char dash = '-';
int i = -1;
String a = "(country)" + dash + "(US)" + dash + i;
Pattern p = Pattern.compile("-", Pattern.LITERAL);
String[] m = p.split(a);
for (String s : m) {
System.out.println(s);
}
}
char dash = '\u2010'; // 2010 is hyphen, 002D is hyphen-minus
int i = -1;
String a = "(country)" + dash + "(US)" + dash + i;
Pattern p = Pattern.compile("\u2010", Pattern.LITERAL);
String[] m = p.split(a);
for (String s : m) {
System.out.println(s);
}
The string representation of an integer always uses the hyphen-minus as the negative sign:
From Integer.toString:
If the first argument is negative, the first element of the result is the ASCII minus character '-' ('\u002D'). If the first argument is not negative, no sign character appears in the result.
so in the end your string has 3 hyphen-minus characters. That's why split can't distinguish between them.
Since you can't change the string representation of an integer, you need to change the dash variable to store a hyphen instead of hyphen-minus. Now there are 2 hyphens and 1 hyphen-minus in your string, making split able to distinguish between them.

How do I split string between From text.charAt() till space occurs in java?

How do I split string between From text.charAt(9) till next space occurs in java?
jhb 9jb 38888 hjbhjb7868hgvhv
I need to extact 38888
you can use
String text = "jhb 9jb 38888 hjbhjb7868hgvhv";
String subStrings[]=text.split(" ");
System.out.println(subString[2]);
You can use substring method twice.
First, get substring from 9th character (till the end of the String)
Get another substring from 0 to index of the first whitespace, for the String retrieved in above step
String s = "jhb 9jb 38888 hjbhjb7868hgvhv";
String subString = s.substring(8);
System.out.println(subString.substring(0, subString.indexOf(" ")));
How about this
String s = "jhb 9jb 38888 hjbhjb7868hgvhv";
System.out.println(s.substring(8, s.length()).split(" ")[0]);
Just takes a substring, and then splits it.
Find the first occurrence of the ninth character:
// If you actually mean the ninth character, pos = 9.
int pos = text.indexOf(text.charAt(9));
Find the next space:
int nextSpace = text.indexOf(' ', pos);
Then take the substring between them:
String part = text.substring(pos, nextSpace);
Note that you may need to handle the case where no space follows, so nextSpace == -1.

Replace leading zeros till decimal point with dash

If a string is a = 000102.45600. I need to convert it to a = ---102.45600.
Any help in java using either regex or String formatter?
Tried the following:
a = a.replaceFirst("^0+(?!$)","-");
but i am getting only a = -102.45600 not 3 dashes.
Rules: Any leading zeros before decimal in string should be replaced by that many dashes.
000023.45677 to ----23.45677
002345.56776 to --2345.56776
00000.45678 to -----.45678
Hopefully I am clear on what my need is?
String subjectString = "000102.45600";
String resultString = subjectString.replaceAll("\\G0", "-");
System.out.println(resultString); // prints ---102.45600
\G acts like \A (the start-of-string anchor) on the first iteration of replaceAll(), but on subsequent passes it anchors the match to the spot where the previous match ended. That prevents it from matching zeroes anywhere else in the string, like after the decimal point.
See: reference SO answer.
This should do it:
String number = //assign a value here
for (int i=number.length();i>0; i--) {
if (number.substring(0,i).matches("^0+$")) {
System.out.println(number.replaceAll("0","-"));
break;
}
}
This searches for the longest substring of number which starts at index 0 and consists entirely of zeroes - starting by checking the entire String, then shortening it until it finds the longest substring of leading zeroes. Once it finds this substring, it replaces each zero with a dash and breaks out of the loop.
Why not convert the start of the string to the "." to an integer, convert it back to a string then compare the lengths. 000102 length = 6. 102 length = 3. You would have your preceding zero count.

replace number to words in right position in java

Actually I'm trying to replace number to words in the sentence that giving by user. This case date format; For example: My birthday is on 16/6/2000 and I'm newbie to the java --> become ---> My birthday is on sixteenth july two thousand and I'm newbie to the java
Here is code:
Scanner reader = new Scanner(System.in);
System.out.println("Enter any numbers: ");
String nom = reader.nextLine(); // get input from user
//checking contains that has "/" or not
if(nom.contains("/")){
String parts[] = nom.split("[/]");
String part1 = parts[0]; //data before "/" will be stored in the first array
String day[] = part1.split("\\s+");// split between space
String get_day = day[day.length -1];// get last array
String get_month = parts[1]; //data in the between of "/" will be stored in the second array
String part3 = parts[2]; // data after "/" will be stored in the third array
String year[] = part3.split("\\s+");// split between space
String get_year = year[0];// get first array
String s = NumberConvert.convert(Integer.parseInt(get_day)) +
NumberConvert.convert(Integer.parseInt(get_month)) +
NumberConvert.convert(Integer.parseInt(get_year));
String con = nom.replaceAll("[0-9].*/[0-9].*/[0-].*", s); // replace number to word
System.out.println(con); // print the data already converted
} else {....}
But the result that I have got is:
My birthday is on sixteenth july two thousand
//"and I'm newbie to the java" is disappear [How to solve it]//
How to solve it. Actually I want to get value before and after of "/" slash and convert it to words and replace it as a original input from user.
What I have tried is:
String con = nom.replaceAll("[0-9].*/[0-9].*/[0-9999]", s); // a bit change [0-9].* to [0-9999]
But output become like this:
My birthday is on sixteenth july two thousand 000 and I'm newbie to the java
//after two thousand index "000" is appearing
The regex is wrong:
[0-9].*/[0-9].*/[0-].*
What it means:
[0-9] match a single number in the range between 0 and 9
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
/ matches the character / literally
[0-9] match a single number in the range between 0 and 9
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
/ matches the character / literally
[0-] match a single number in the list 0- literally
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
It should be:
[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]
Or, better:
\d{2}/\d{2}/\d{4}
You can also use below regex pattern to get all the numbers from String:
String st = "My birthday is on 16/6/2000 and I'm newbie to the java, using since 2015";
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(st);
while (m.find()) {
System.out.println(m.group());
}

Wind blowing on String

I have some basic idea on how to do this task, but I'm not sure if I'm doing it right. So we have class WindyString with metod blow. After using it :
System.out.println(WindyString.blow(
"Abrakadabra! The second chance to pass has already BEGUN! "));
we should obtain something like this :
e a e a a ea y
br k d br ! Th s c nd ch nc t p ss h s lr d B G N!
A a a a a e o o a E U
so in a nutshell in every second word we pick every vowels and move them one line above. In the second half of words we move vowels one line below.
I know I should split string to tokens with tokenizer or split method,but what next ? Create 3 arrays each representing each row ?
Yes, that's probably an easy (not very performant) way to solve the problem.
Create 3 arrays; one is filled with the actual data and 2 arrays are filled (Arrays.fill) with ' '.
Then iterate over the array containing the actual data, and keep an integer of which word you're currently at and a boolean if you already matched whitespace.
While iterating, you check if the character is a vowel or not. If it's a vowel, check the word-count (oddness/evenness) and place it in the first or third array.
When you reach a whitespace, set the boolean and increase the word count. If you reach another whitespace, check whether the whitespace is already set: if so, continue. If you match a non-whitespace, reset the whitespace boolean.
Then join all arrays together and append a new-line character between each joined array and return the string.
The simplest way is to use regex. This should be instructive:
static String blow(String s) {
String vowels = "aeiouAEIOU";
String middle = s.replaceAll("[" + vowels + "]", " ");
int flip = 0;
String[] side = { "", "" };
Scanner sc = new Scanner(s);
for (String word; (word = sc.findInLine("\\s*\\S*")) != null; ) {
side[flip] += word.replaceAll(".", " ");
side[1-flip] += word.replaceAll("[^" + vowels + "]", " ");
flip = 1-flip;
}
return String.format("|%s|%n|%s|%n|%s|", side[0], middle, side[1]);
}
I added the | characters in the output to show that this processes excess whitespaces correctly -- all three lines are guaranteed the same length, taking care of leading blanks, trailing blanks, or even ALL blanks input.
If you're not familiar with regular expressions, this is definitely a good one to start learning with.
The middle is simply the original string with all vowels replaced with spaces.
Then, side[0] and side[1] are the top and bottom lines respectively. We use the Scanner to extract every word (preserving leading and trailing spaces). The way we process each word is that in one side, everything is replaced by blanks; in the other, only non-vowels are replaced by blanks. We flip sides with every word we process.

Categories

Resources