Tooilia
Tooilia

Reputation: 39

Break apart a string by character position

Suppose I have a number that was entered by a user

Scanner input = new Scanner(System.in);

System.out.println("Input a number.");

String num = input.next();

num must have a length of 50, which is implemented by a boolean method.

How can I create a new string that takes only the first 45 digits of the num?

Example entered string "123456789"

Needed only the first 5 numbers of String num "12345"

Could I convert the string to an int and use modulus?

Upvotes: 1

Views: 466

Answers (2)

Lews Therin
Lews Therin

Reputation: 10995

try
{
   String substr = num.subString(0,45) ;
}
catch(IndexOutOfBoundsException exception)
{

   System.out.println(exception) ;

}

To explain: subString(index, length)

index is the position you want to start the operation and length the amount of string you want. If length specified is greater than length of string, you get an IndexOutOfBoundsException, which I catch in the try catch block

Upvotes: 2

PermGenError
PermGenError

Reputation: 46428

use string.substring() metod from java API.

String output = num.subString(0,45) ;

Upvotes: 2

Related Questions