Home > Mobile >  Java find the words before and after a dash
Java find the words before and after a dash

Time:06-03

If I have a sentence as a String and within that sentence is a dash, how can I easily find the words before and after the dash, knowing the position in the String of the dash (as a number). For examples below, should return "Smith", "Johnson" in all cases (perhaps as two Strings or an array):

"My name is Smith-Johnson." (pos=16)

"My name was O'Connor-Peters but now is Smith-Johnson and I'm glad" (pos=44)

"Smith-Johnson is my name" (pos=5)

"Yo!Smith-Johnson, come here!" (pos=8)

"Come here Smith-Johnson" (pos=15)

Assume the char at pos is known to be a dash. The test cases illustrate some examples with punctuation, so you can't simply walk forward and backward until you find a space.

My thought is to walk forward and backward until !Character.isLetter() is true, checking for fenceposts (start and end of String). But it gets messy. Is there a simpler way? Maybe a regex expression?

Thanks in advance.

CodePudding user response:

You could attempt to split the string into an array of strings using the hyphen character, and then split the subsequent array elements into words based on spaces. Finding the last and first element of the resulting arrays would be fairly easy.

The java String object has a method called split which returns an array of strings.

This should be a good start for you.

There might be a regex solution, when I'm playing with regex I typically head here https://regex101.com/ and see what works.

CodePudding user response:

        String s = "My name was O'Connor-Peters but now is Smith-Johnson and I'm glad";
        String wordAfter = s.substring(pos   1).split("\\s")[0]; // first word after
        String[] before = s.substring(0, pos).split("\\s");
        String wordBefore = before[before.length - 1];
        System.out.println(wordAfter);
        System.out.println(wordBefore);

CodePudding user response:

String s = "My name was O'Connor-Peters but now is Smith-Johnson and I'm glad"; int pos = 44;

  String[] parts = s.split("-");
  String[] solution = {"",""};
  
  
  int index = 0;
  
  for(int i = 0; i < parts.length; i  ){
      
      index  = parts[i].length();
      
      if(index > pos){
          
          String[] w1 = parts[i-1].split(" ");
          String[] w2 = parts[i].split(" ");
          
          solution[0] = w1[w1.length -1];
          solution[1] = w2[0];
          
      }
      
      
          
      
      
  }
  System.out.println(solution[0]);
  System.out.println(solution[1]);
  • Related