0

The question is:

Write a function untilSpace(s) that returns a substring of s starting at the beginning and extending until a space is found. The space is not included in the returned value. The argument will always have a space.

Examples:

untilSpace("ab cde") -> "ab"

My code solution is:

public String untilSpace(String s){
    String str = s;
    str = str.replaceFirst(" ", "");
    System.out.println(str);
    return str;  
}

I managed to remove the space, but I still need to find a way to remove the rest of the string that comes after the space.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Beginner
  • 11
  • 3
  • 1
    Does this answer your question? [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Matthew Kerian Feb 16 '21 at 00:16
  • 1
    This is not a dupe of using split. Using split is *one* way of doing it, but not the required way or even necessarily a "better" way. – Bohemian Feb 16 '21 at 00:47

2 Answers2

2

Use regex replace:

public String untilSpace(String s) {
    return s.replaceAll(" .*", "");
}

This works by replacing everything matched by the regex expression with nothing - effectively deleting it.

The regex " .*" means "a space followed by any chars to the end of input".

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    Unless I'm mistaken he essentially wants str.split(" ")[0] – Matthew Kerian Feb 16 '21 at 00:17
  • I think this is a fairly unusual way to solve it. Given that there is `split` (also with match-limiting) and `indexOf` + `substring`. But sure, works, upvoted. – Zabuzard Feb 16 '21 at 00:29
  • @Zabuzard actually replaceAll is a far more general way to extract near-arbitrary parts of a String. Using split assumes the start and end of the target are splittable there, plus split does much more work. – Bohemian Feb 16 '21 at 00:44
  • @MatthewKerian in this case, yes. But in the general case, split is not as versatile as replaceAll - see previous comment. – Bohemian Feb 16 '21 at 00:45
1

split

You can split the string on space and use the first element:

String firstWord = text.split(" ")[0];

You can also improve this approach by limiting the amount of elements you are interested in (in case there are lots of spaces):

String firstWord = text.split(" ", 2)[0];

indexOf + substring

A more manual approach involving indexOf and substring also works well:

int index = text.indexOf(' ');
String firstWord = text.substring(0, index);

Note that this approach will crash if there is no space contained in text, due to indexOf returning -1 which is an invalid index for substring. But in your case it is fine since your task says

The argument will always have a space.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82