1

How can I get a list of characters in a string that come after a substring? Is there a built-in String method for doing this?

List<String> characters = new ArrayList<>();
String string = "Grid X: 32";
// How can I get the characters that come after "Grid X: "?

I know you could do this with a loop, but is there another way that may be simpler?

1
  • You could try a split on the word "Grid X:" and then select from the resulted array the first element[position 0] or your could split by ":" Commented Dec 7, 2014 at 19:31

4 Answers 4

1

Just grab the characters after the ": "

String string = "Grid X: 32"
int indexOFColon = string.indexOf(":");
String endNumber = string.subString(indexOFColon + 2);

So you get the index of the colon, which is 6 in this case, and then grab the substring starting 2 after that, which is where your number starts.

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

Comments

1

There are two possibilities:

  1. Use a regular expression (regex):

    Matcher m = Pattern.compile("Grid X: (\\d+)");
    if (m.matches(string))
    {
        int gridX = Integer.parseInt(m.group(1));
        doSomethingWith(gridX);
    }
    
  2. Use the substring method of the string:

    int gridX = Integer.parseInt(string.substring(string.indexOf(':')+1).trim());
    doSomethingWith(gridX);
    

Comments

1

Below code can be used for getting list of chacters :-

String gridString = "Grid X: 32";

String newString = gridString.subSubString(gridString.indexOf(gridString ) +  gridString    .length );
char[] charArray = newString.toCharArray();
Set nodup = new HashSet(); 
for(char cLoop : charArray){
nodup.add(cLoop);
}

Comments

0

There is more than one way to get this done. The simplest is probably just substring. But it is fraught with danger if the string doesn't actually start with "Grid X: "...

String thirtyTwo = string.substring( s.indexOf("Grid X: ") + "Grid X: ".length() );

Regex is pretty good at this too.

1 Comment

I gave you one because I do not see any explanation of down voter

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.