1

For example I have this string: Hello, world! and I want to get Hello by using indexes. Is there a function like

package com.example;

import static java.lang.String.getStringBetweenIndex;

public class Example {
    public static void main(String[] args) {
        String hello = "Hello, world!";

        System.out.println(hello.getStringBetweenIndex(0, 5));
    }
}

that gives output Hello?

2
  • You titled and tagged this question substring, have you tried that? Commented Dec 30, 2020 at 13:22
  • I never knew that. Commented Dec 30, 2020 at 13:33

2 Answers 2

2

You can use *.substring(firstIndex, secondIndex); method for that. Try;

package com.example;

public class Example {
    public static void main(String[] args) {
        String hello = "Hello, world!";

        System.out.println(hello.substring(0, 5));
    }
}

Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. Examples:

  • "hamburger".substring(4, 8) returns "urge"
  • "smiles".substring(1, 5) returns "mile"

Parameters:

  • beginIndex - the beginning index, inclusive.
  • endIndex - the ending index, exclusive.

Returns:

the specified substring.

Throws:

  • IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

Source: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#substring(int,int)

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

1 Comment

Nice, a good answer with documentation link.
2
public String substring​(int beginIndex, int endIndex)

Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. Examples:

  • "hamburger".substring(4, 8) returns "urge"
  • "smiles".substring(1, 5) returns "mile"

Parameters:

  • beginIndex - the beginning index, inclusive.
  • endIndex - the ending index, exclusive.

Returns:

  • the specified substring.

Throws:

  • IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

Source: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#substring(int,int)

1 Comment

Thank you! It really helps.

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.