Skip to main content

APIzation: Replication Package

[Q#8871682][A#8871710] how to find before and after sub-string in a string

https://stackoverflow.com/q/8871682

I have a string say 123dance456 which I need to split into two strings containing the first sub-string before the sub-string dance (i.e. 123) and after the sub-string dance (i.e. 456). I need to find them and hold them in separate string variables, say String firstSubString = 123; and String secondSubString = 456;. Is there any given String method that does just that?

Answer

https://stackoverflow.com/a/8871710

You can use String.split(String regex). Just do something like this: Please note that if "dance" occurs more than once in the original string, split() will split on each occurrence – that's why the return value is an array.

APIzation

String s = "123dance456";
String[] split = s.split("dance");
String firstSubString = split[0];
String secondSubString = split[1];
package com.stackoverflow.api;

public class Human8871710 {

  public static String[] findPreAndSucOfSubString(String s, String sub) {
    String[] split = s.split(sub);
    String firstSubString = split[0];
    String secondSubString = split[1];
    String[] result = new String[2];
    result[0] = firstSubString;
    result[1] = secondSubString;
    return result;
  }
}

package com.stackoverflow.api;

/**
 * how to find before and after sub-string in a string
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/8871710">https://stackoverflow.com/a/8871710</a>
 */
public class APIzator8871710 {

  public static String find(String s) throws Exception {
    String[] split = s.split("dance");
    String firstSubString = split[0];
    return split[1];
  }
}