Extract number from a String - java

i have a large String which includes numbers and text.
Now i want exactly a number from that string.
The number starts every time with a '6' and three '0' but then the number can be different digits.
For example here is a try:
String text1 = "ID 6 IDENTIFICATION NUMBER 600026821 NAME: BECK POSTCODE 60025";
if(text1.contains("6000"))
{
System.out.println(text1.indexOf("6000"));
}
So as you can see the String can also contains postcode digits and ids.
But the number i want has always the same length of 9 digits and starts with '6000...'.
So how can i extract that number?
Thanks
EDIT
Ok now i try this one:
String index = "6000";
String text1 = "ID 6 IDENTIFICATION NUMBER 600026821 NAME BECK POSTCODE 60025";
System.out.println(text1.indexOf(index));
String number = text1.substring(text1.indexOf(index), text1.lastIndexOf(text1.indexOf(index) + 5));
System.out.println(number);
It starts but ends not correctly

Regex can be used like this :
public static void main(String args[]) {
String text1 = "ID 6 IDENTIFICATION NUMBER 600026821 NAME: BECK POSTCODE 60025";
System.out.println(text1.replaceAll(".*?\\b(6000\\d+)\\b.*", "$1")); // replace everything except a number that starts with 6 and is followed by 000 with "".
}
O/P :
600026821
Note : You can use (6000\\d{5}) instead of (6000\\d+) if you are certain that the number of digits will be 9.

for (String word : s.split(" ")) {
int number = 0;
if (word.startsWith("6000"))
number = Integer.parseInt(word);
}
}
EDIT
I hadn't read that the number you wanted is always of length 9. In that case, check its length in the if condition:
if (word.startsWith("6000") && word.length() == 9)

Like that:
System.out.println(text1.substring(text1.indexOf("6000"),text1 .indexOf("6000")+9));
int value=Integer.parseInt(text1.substring(text1.indexOf("6000"),text1 .indexOf("6000")+9));

Once you have the index of the "6000" just continue, you already said that the length is always 9
int start = text1.indexOf("6000");
String yourNumber = text1.substring(start, start+10);

You can do it like this to get all numbers in that string that follow your rules. Note that I added some more numbers to text1 for testing purposes.
package so;
public class NumberExtractor {
public static void main(String[] args) {
String text1 = "ID 6 IDENTIFICATION NUMBER 600026821 NAME: BECK 600026822600026823 POSTCODE 60002682460025";
boolean notAtTheEnd = true;
int currentIndex = 0;
while (notAtTheEnd) {
int start = text1.indexOf("6000", currentIndex);
if (start > -1) {
String number = text1.substring(start, start + 9);
currentIndex = start + 1;
System.out.println(number);
} else {
notAtTheEnd = false;
}
}
}
}

Related

Method to check if the string contains certain elements that accepts a parameter String

I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```

How to split an input of numbers (student ID) from user to implement into formula

I'm having trouble with this beginner java program that was assigned to me, I'm completely new to java and I'm having a lot of trouble with this particular program. These are the instructions:
Your program should prompt users to enter an n-digit number as a student ID, and then display the
validity of the entered ID. You can assume n will be in the range of 6 and 10 inclusive. The checksum
digit is part of student ID. Your algorithm is to match the rightmost digit in the entered ID with the
computed checksum digit. If there is no match, then your program shall report the entered ID being
invalid.
For example, the entered ID 1234567 is invalid because the computed 7th digit is 1 (= (1 * (digit1) + 2 *
(digit 2) + 3 * (digit 3) + 4 * (digit 4) + 5 * (digit 5) + 6 * (digit 6)) % 10) and is different from the actual 7th digit which is
7. However, if the entered ID is 1234561 your program shall display a message of acceptance.
The first step I'm trying to do is to read each number from the user's input that doesn't have spaces, as if it were to have spaces. Then I'm trying to get each of those numbers assigned to the variable that is digit 1, digit 2, ... etc. to compute.
import java.util.Scanner;
public class H4_Ruby{
public static void main(String[] args){
// this code scans the the user input
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a student ID between 6-10 digits");
String nums = scan.nextLine();
String[] studentIdArray = nums.split(" ");
int[] studentID = new int [studentIdArray.length];
for (int i = 0; i < studentIdArray.length; i++)
{
studentID[i]= Integer.parseInt(studentIdArray[i]);
System.out.print(studentID[i] + ",");
}
}
That is my code so far...
You can't split by nums.split(" ") to get a String array. You already got a String Id from user without spaces.
So iterate through the String and keep calculating the sum of products with multiplier like below. I've added comments in the code itself.
public static void main(String[] args) {
// this code scans the the user input
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a student ID between 6-10 digits");
String nums = scan.nextLine();
int multiplier = 1, totalProductSum = 0;
for (int i = 0; i < nums.length() - 1; i++) {
// if the character is not digit, its not a valid id
if (!Character.isDigit(nums.charAt(i))) {
System.out.println("Invaild Id");
return;
}
// maintain the sum of products and increment the multiplier everytime
totalProductSum += (multiplier * (nums.charAt(i) - '0'));
multiplier++;
}
// the condition for validity i.e totalProduct sum mod 10 and last digit in input Id
if ((totalProductSum % 10) == (nums.charAt(nums.length() - 1) - '0'))
System.out.println("Valid Id");
else
System.out.println("Invaild Id");
}
Here, you can use this one also:
final class H4_Ruby {
public static void main(final String... args) {
System.out.printf("%s student ID%n", (H4_Ruby.isValid(H4_Ruby.read())) ? "Valid" : "Invalid");
}
private static String read() {
final Scanner scan = new Scanner(System.in);
// [start] do-while here for input validation: length and all characters must be digits
System.out.print("Please, enter a student ID between 6-10 digits: ");
final String input = scan.nextLine();
// [end] do-while here for input validation: length and all characters must be digits
return input;
}
private static boolean isValid(final CharSequence studentId) {
int partial = 0;
for (int i = 0; i < (studentId.length() - 1); i++) {
partial += ((i + 1) * Character.getNumericValue(studentId.charAt(i)));
}
return (partial % 10) == Character.getNumericValue(studentId.charAt(studentId.length() - 1));
}
}

how to replace some character's of String

I have a numeric String i want to change the String first three character's by another character
Suppose I have a String like 0333XXXXXXX and +38333XXXXXXX. if the first character of String is +38 i want to replace it with "0" while remaining String remain the same Here is my code
private String modifyNumber(String num) {
if (num.startsWith("+38")) {
num.replaceFirst("+38", "0");}
return num;}
"+38" is not accepting in num.replaceFirst.
You can use string replace method. see below
String number = +9231235410;
String newNumber = number.replace("+92","0");
EDIT:
this one is base on your code
private String modifyNumber(String num) {
if (num.startsWith("+92")) {
num = num.replaceFirst("\\+(92)", "0");}
return num;}
Note:
In java, you need to have double backslash since the \ is a unique
java character.
Java strings are immutable method. you need to assign it to a variable to have the result. num = num.replaceFirst("\\+(\\d{2})", "0")
you can use substr() and concat with '0' like,
String str= "+919025858316";
String newstr ="";
if(str.substring(0,3).equals("+91"))
{
newstr = "0" + str.substring(3);
}
else
{
newstr = str;
}
System.out.println(newstr);
output is 09025858316
Check like this :
String num = "+921231231231"; // OR String num = "01231231231";
if(num.startsWith("+92")) {
String a = "0" + num.substring(3);
System.out.println("" + a);
}else{
System.out.println("" + num);
}
Update:
private String modifyNumber(String num) {
if(num.startsWith("+92")) {
num = "0" + num.substring(3);
}
return num;
}
you can just get the last 10 digit of the string and then you can add the zero.
might be that help you
String number= str.substring(Math.max(str.length() - 10, 0));
number ="0"+number;
from here you can get the correct phone number without any code.
might be this help you.Thanks
There is some standardization on mobile numbers in every country. The mobile number is 10 digit. Only here, the last 10 digits are mobile numbers and rest of the digits are country code so take the last 10 digit and add 0 to the first. Then, your problem will be resolved.
i.e,
String number = "+929918001800";
String newNumber = "0"+number.subString(number.length()-10,number.length());
I hope this one will help you :)

Adding contents of a String,where string s="12 computer 5 7"

In an interview they asked me this question.There is a string like "12 computer 5 7". You need to add integers within that string and answer should be 24.How can i solve this can anyone help me please.
string s="12 computer 5 7"
output should be:24
Can i use sub-string or some other process to solve it
Try this,
String input = "12 computer 5 7";
String[] splittedValue = input.split(" "); // splitted the values by space
int result = 0;
for (String s : splittedValue)
{
if (s.matches("\\d+")) // check while the input is number or not
{
result = result + Integer.parseInt(s); // parse it and add it to the count
}
}
System.out.println("Result : "+result);
Use split("[ ]") to convert the string into an array of strings separated by space and then add the integers present in each position of the array. Add it to sum if it is an integer like :-
String ar[] = s.split("[ ]");
int sum = 0;
for(int i=0;i<ar.length;i++){
try{
sum += Integer.parseInt(ar[i]);
}catch(NumberFormatException){
//not an integer.
}
}
System.out.println("Sum of integers : "+sum);
public class Main{
public static void main(String []args){
String s="12 computer 5 7";
String [] candidateNumbers = s.split(" ");
int sum = 0;
for (String num:candidateNumbers) {
try {
sum+=Integer.parseInt(num);
} catch (Exception e) {
//
}
}
System.out.println(sum);
}
}
Using Java 8 you could also write:
int sum = Arrays.stream(s.split("\\D+"))
.mapToInt(Integer::parseInt)
.sum();
Splitting on non digit characters returns an array containing the 3 numbers as strings. Note that this assumes that the input string is well formed.

moving the characters in a text string a specified number of positions

I am new in programming and I am trying to write a program that moves the characters in a text string a specified number of positions.
The program must include a method whose inputs will be a text string (type String) and the number of positions (type int). The output will be a string with characters shifted.
For example, moving 4 positions:
rabbit eats a carrot
it eats a carrotrabb
Now I have this partial code. I can erase first characters but I don't know how to put them to the end of this text. How can i make it?
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
char firstLetter = a.charAt(0);
b--;
a = a.substring(b);
String m = a + firstLetter ;
System.out.println("now it is "+ m);
}
If you use regex, it's just one line:
return str.replaceAll("^(.{" + n + "})(.*)", "$2$1");
import java.util.*;
public class JavaApplication5 {
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
String firstPart = a.substring(0,b); // line 1
b--;
a = a.substring(b);
String m = a + firstPart ; // line 2
System.out.println("now it is "+ m);
}
}
See the changes above in statement marked with comment line 1 and line 2.
In line 1, we are getting the first part of string and in line 2, adding at the end of second string part.
public String foo(String s, int n) {
String s2 = s.substring(0, n);
s = s.substring(n) + s2;
return s;
}
you can put a few validations on this, like null string or n is less than s.length() etc.
It is better to use modulus operator to calculate number of shifts. When initial number of shift is more than string length. Check this :
public String shift(String string,int n){
int nshift = string.length() < n ? n%string.length() : n ;
String a = string.substring(0,nshift);
return string.substring(nshift) + a ;
}
One more version. All the work is essentially done in 1 line here:
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
Anyway, the full code is:
import java.util.*;
public class ShiftLetters {
public static void main(String[] args) {
System.out.print("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.print("Enter number of positions: ");
int b = cti.nextInt();
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
System.out.println(result);
}
}
Also, you might want to be more accurate with your indentation style to improve readability.

Categories

Resources