3

I have a string, and I want to extract the text abcd from this string. I useed the indexOf() method to get the start index, but how we can I set the end index value? The abcd text value is dynamic, so we can't hardcode it like startIndex()+5. I need some logical code.

String str = "Hi Welcome to stackoverflow : " +"\n"+"Information :"+"\n"+"hostname : abcd"+"\n"+
"questiontype : text"+"value : desc.";

if(str.contains("hostname : "))
{
String value = "hostname : "
int startIndex = str.indexof("hostname : ") + value.length();
// how to find the endIndex() in that case
}

4
  • 1
    These may be useful: String::substring, String::indexOf, String::length. Commented Dec 15, 2020 at 12:36
  • You can look for what comes after the abcd-value and use this information to get an endIndex. Commented Dec 15, 2020 at 12:38
  • How to find the end index? The question is the answer: it depends on what defines the end of the text. Commented Dec 15, 2020 at 12:40
  • You can't really know how long the remaining value is, unless you specify a structure to which this text conforms. It seems that after each value, a newline is present, so you could simply search for the newline after the key with str.substring(startIndex, str.indexOf("\n", startIndex)). Commented Dec 15, 2020 at 12:43

3 Answers 3

2
String answer = str.substring( str.indexOf( value) + value.length(), str.indexOf( "questiontype :" ) );
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to get the string after "hostname : " you can do:

String str = "Hi Welcome to stackoverflow : " +"\n"+"Information :"+"\n"+"hostname : abcde"+"\n"+
        "questiontype : text"+"value : desc.";
    

int startIndex = str.indexOf("hostname") + "hostname : ".length();
int endIndex = str.indexOf("questiontype") - 1;

String result = str.substring(startIndex, endIndex);

System.out.println(result);

Also note that you can add \n to the text of the string without needing to append it so that: "Hi Welcome to stackoverflow : " +"\n"+"Information..." would work just as fine doing: "Hi Welcome to stackoverflow : \nInformation..."

Comments

0

Perhaps not as efficient as the answers with indexOf, a regex solution is succint.

Optional<String> getValue(String properties, String keyName) {
    Pattern pattern = Pattern.compile("(^|\\R)" + keyName + "\\s*:\\s*(.*)(\\R|$)");
    Matcher m = pattern.matcher(properties);
    return m.find() ? Optional.of(m.group(2)) : Optional.emtpy();
}

String hostname = getValue("...\nhostname : abc\n...", 
                           "hostname").orElse("localhost");

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.