How to "sscanf" in Java? [duplicate] - java

This question already has answers here:
what is the Java equivalent of sscanf for parsing values from a string using a known pattern?
(8 answers)
Closed 5 years ago.
I have a string and I want to a) check if it matches the following format and b) extract the numbers and text into variables:
"x:x:x - some text" // x = some integer number
In, C, I would use :
sscanf(str1, "%d:%d:%d - %s\n", &x, &y,&z, str2);
How do I do the same in Java?

Did you mean :
String text = "1:99:33 - some text";
boolean check = text.matches("\\d+:\\d+:\\d+ - .*");
System.out.println(check);
If you want to match exact (one number):(two numbers):(two number) you can use \\d:\\d{2}:\\d{2} instead of \\d+:\\d+:\\d+
details
\\d+ match one or more digit
: literal character
\\d+ match one or more digit
: literal character
\\d+ match one or more digit
- one space hyphen one space
.* zero or more any character
...how do I extract the numbers and the text from the string?
If you are using Java 8 you can split your input, the first input return numbers separated by :, the second is the text you want, so to extract the numbers, you need to split the first input again by : then Iterate over them and convert each one to an Integer, like this :
String input = "1:99:33 - some text";
String[] split = input.split(" - ");//Split using space hyphen space
String text = split[1];//this will return "some text"
List<Integer> numbers = Arrays.asList(split[0].split(":")).stream()
.map(stringNumber -> Integer.parseInt(stringNumber))
.collect(Collectors.toList());// this will return list of number [1, 99, 33]

The alternatve solution:
String input = "1:99:33 - some text";
StringTokenizer st = new StringTokenizer(input, ":");
while (st.hasMoreTokens()) {
String token = st.nextToken();
System.out.println(token);
}
StringTokenizer break the string into tokens. Where ":" is a tokens delimiter.
Output:
1
99
33 - some text

Related

Search for a general sub-string within a string in Java [duplicate]

This question already has answers here:
How to get substrings from strings [duplicate]
(4 answers)
Closed 4 years ago.
I am new to Java. I want to ask how to search for a general sub-string within a given string.
For example:-
In the string 12345.67 I want to search for the sub-string .67
And in the string 1.00 I want to search for the string .00.
I basically want to search for the string after the radical (.), provided the number of characters after radical are only 2.
According to my knowledge search for general sub-string is not possible, I thereby asked for your help.
I wish to print the input (stored in the database) , a floating point number, into Indian Currency format, i.e, comma separated.
I even looked at various previous posts but none of them seemed to help me as almost everyone of them failed to produce the requite output for decimal point
According to my knowledge search for general sub-string is not possible
So you may learn a bit more, here String substring(int beginIndex) method :
String str = "12345.67";
String res = str.substring(str.indexOf('.')); // .67
If you want to check that there is only 2 digits after . :
String str = "12345.67";
String res = str.substring(str.indexOf('.') + 1); // 67
if(res.length() == 2)
System.out.println("Good, 2 digits");
else
System.out.println("Holy sh** there isn't 2 digits);
You can use split plus the substring to achieve your objective
String test = "12345.67";
System.out.println(test.split("\\.")[1].substring(0,2));
In the split function, you can pass the regex with which you could give the separator and in a substring function with the number of characters you want to extract
Next to the answer provided from #azro you may also use regex:
String string = "12345.67";
Pattern ppattern = Pattern.compile("\\d+(\\.\\d{2})");
Matcher matcher = pattern.matcher(string);
if(matcher.matches()){
String sub = matcher.group(1);
System.out.println(sub);
}
Which prints:
.67
String str = "12345.67";
String searchString = "." + str.split("\\.")[1];
if(str.contains(searchString)){
System.out.println("The String contains the subString");
}
else{
System.out.println("The String doesn't contains the subString");
}

Strip all whitespaces in string and convert it to an array in Java [duplicate]

This question already has answers here:
How to split a string with any whitespace chars as delimiters
(13 answers)
Closed 5 years ago.
I'm looking for a way to convert a string to an array and strip all whitespaces in the process. Here's what I have:
String[] splitArray = input.split(" ").trim();
But I can't figure out how to get rid of spaces in between the elements.
For example,
input = " 1 2 3 4 5 "
I want splitArray to be:
[1,2,3,4,5]
First off, this input.split(" ").trim(); won't compile since you can't call trim() on an array, but fortunately you don't need to. Your problem is that your regex, " " is treating each space as a split target, and with an input String like so:
String input = " 1 2 3 4 5 ";
You end up creating an array filled with several empty "" String items.
So this code:
String input = " 1 2 3 4 5 ";
// String[] splitArray = input.split("\\s+").trim();
String[] splitArray = input.trim().split(" ");
System.out.println(Arrays.toString(splitArray));
will result in this output:
[1, , , , , , , , 2, 3, 4, , , , , , 5]
What you need to do is to create a regex that greedily groups all the spaces or whitespace characters together, and fortunately we have this ability -- the + operator
Simply use a greedy split with the whitespace regex group
String[] splitArray = input.trim().split("\\s+");
\\s denotes any white-space character, and the trailing + will greedily aggregate one or more contiguous white-space characters together.
And actually, in your situation where the whitespace is nothing but multiples of spaces: " ", this is adequate:
String[] splitArray = input.trim().split(" +");
Appropriate tutorials for this:
short-hand character classes -- discusses \\s
repetition -- discusses the + also ? and * repetition characters
Try:
String[] result = input.split(" ");

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());
}

regex to split string like "ABC123XYZ111" in java [duplicate]

This question already has an answer here:
Split string in alphabet and number
(1 answer)
Closed 6 years ago.
I have a string like ABC123XYZ111 so that regex should be able to split last numeric part as one part and from starting to start of last numberic value si one part,
eg : I want to split into two parts
first part should contain ABC123XYZ and
second part should be 111
first part may contain numeric values but second part should be numeric.
This worked for me
myString.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
Keep it simple then.
String root = s.replaceAll("^(.*?)(\\d+)$", "$1");
String number = s.replaceAll("^(.*?)(\\d+)$", "$2");
^(.*?)(\\d+)$
^ = begin of string
$ = end of string
.*? = shortest sequence of any character
\d+ = digit, one or more
( ... ) = group numbered from 1, $1, $2, ...
You can use this regex
(.*?)(?=\d+$)(.*)
Java Code
String line = "ABC123XYZ111";
String pattern = "(.*?)(?=\\d+$)(.*)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
}
IDEONE DEMO

Extracting numbers from a string in java [duplicate]

This question already has answers here:
How to extract numbers from a string and get an array of ints?
(13 answers)
Closed 4 years ago.
I have a string like this 3x^2 I want to extract the first and the second number and store them in an array. and if they didn't exist they should be considered as 1.
EDIT :
For example in string x the first and the second number are 1
or in string 3x the second number is 1. I think it should be clear now.
Just get digits with the Regex:
String str = "3x^2";
String pattern = "(\\d+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
ArrayList<Integer> numbers = new ArrayList<>();
Find with Matcher all numbers and add them to the ArrayList. Don't forget to convert them to int, because m.group() returns the String.
while (m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
And if your formula doesn't contain the second number, add there your desired default item.
if (numbers.size<2) {
numbers.add(1);
}
Finally print it out with:
for (int i: numbers) {
System.out.print(i + " ");
}
And the output for 3x^2 is 3 2.
And for the 8x it is 8 1.
if the numbers are allways separated by x^, just split the string using this separator
String[] splitted = "3x^2".split("x\\^");

Categories

Resources