Home > Software engineering >  Split string from character index until whitespace
Split string from character index until whitespace

Time:04-25

I have a string that goes something like this

330 Daniel T92435

Now I need Daniel, and I could simply just type

string.substring(4,11);

But the information where "Daniel" is right now could vary, and I don't want to use the split[] method. I was thinking if there was a way to make the substring method read data until a whitespace is found.

CodePudding user response:

If input string always has the following string structure "someSymbols Name someSymbols" you can use the following regular expression to extract the name:

"[^\\s] \\s (\\p{Alpha} )\\s [^\\s] "
  • \\p{Alpha} - alphabetic character;
  • \\s - white space;
  • [^\\s] - any symbol apart from the white space.

In the code below Pattern is as object representing the regular expression. In turn, Matcher is a special object that is responsible for navigation over the given string and allows discovering the parts of this string that match the pattern.

public static String findName(String source) {
    Pattern pattern = Pattern.compile("[^\\s] \\s (\\p{Alpha} )\\s [^\\s] ");
    Matcher matcher = pattern.matcher(source);
    String result = "no match was found";
    if (matcher.find()) {
        result = matcher.group(1); // group 1 corresponds to the first element enclosed in parentheses (\\p{Alpha} )
    }
    return result;
}

main()

public static void main(String[] args) {
    System.out.println(findName("330 Daniel T92435"));
}

Output

Daniel

CodePudding user response:

You can use the str.indexOf(" ") function.

int start = string.indexOf(" ") 1;
string.substring(start,start   7);

Edit: You can use

int start = string.indexOf(" ") 1;
int end = string.indexOf(" ", start 1);
string.substring(start,end >= 0 ? end : string.length());

if you want to select the first word and don't know how long it will be.

  • Related