0

I've been trying that, but without much success:

String whatIShouldSay = "no more beer please!";
String whatIActuallySay = whatIShouldSay.substring(3,-1);
System.out.println (whatIActuallySay);

But it doesn't work like that. But why so? What could I do instead? As a workaround I could do:

whatIShouldSay.substring(3,whatIShouldSay.length());

But that doesn't feel like an elegant solution to me. Would be grateful for a hint! :)

P.S.: Would you write "should" in "whatIShouldSay" with a lowercase or with an uppercase "s"?

2
  • 2
    There is an other substring method which takes only one parameter, which is the inclusive begin index. The returned string always ends where the original string ends. Commented Jan 11, 2021 at 12:32
  • To answer your P.S.: it should is clearly upper case, there's no good reason to not do that. One area where this answer is not quite as clear are abbreviations that are usually written in ALL-CAPS (such as HTTP) which lead to weird names. The Google Java code style has a nice discussion on the topic of corner cases for camel case. Commented Jan 11, 2021 at 12:35

1 Answer 1

4

The one-argument variant of substring will return the string starting from the argument up to the end:

String whatIActuallySay = whatIShouldSay.substring(3);

Note that the convention of using negative indices to count from the back of some sequence is almost never used in Java (never in the core libraries, as far as I know and very rarely in third-party libraries).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.