DLR
DLR

Reputation: 187

Split a string into only 3 characters. Java

I need to take a string of so many characters and make it to only 3. For example, if I have read in a string "November" I want to convert it to "Nov". I was wondering what the operation would be to do this if:

       String month = "November";
       //I want month = "Nov"

I have to do this for many different months. I tried using the .replace() but I could not figure out the correct regexp to get it to delete everything after the third character.

Upvotes: 0

Views: 2075

Answers (3)

borism
borism

Reputation: 111

Try

month.substring(0, 3);

For details see: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#substring(int)

Upvotes: 2

sunysen
sunysen

Reputation: 2351

String month = "November";

month = month.substring(0, 3);

Upvotes: 3

rgettman
rgettman

Reputation: 178303

You don't need regex for this task. If the length of month is more than 3, then call the substring method. It takes two parameters -- one for the beginning position of the substring (inclusive), and one for the ending position of the substring (exclusive). Indices are 0-based.

Upvotes: 5

Related Questions