5
$\begingroup$

How can I split a string at the first space character in it?

For example, "First I. Last, Jr." should become {"First","I. Last, Jr."}.

$\endgroup$

3 Answers 3

14
$\begingroup$

Use the third argument of StringSplit to split input string into at most 2 substrings:

str = "First I. Last, Jr.";

StringSplit[str, " ", 2]
{"First", "I. Last, Jr."}
$\endgroup$
3
$\begingroup$

Using string pattern or regex

StringCases["First I. Last, Jr.",StartOfString~~Shortest[head___]~~" "~~Longest[tail___]~~EndOfString:>{head,tail}]

StringCases["First I. Last, Jr.",RegularExpression["^(\\S*?)(\\s)(.*)$"]:>{"$1","$3"}]

{{"First", "I. Last, Jr."}}
```
$\endgroup$
1
$\begingroup$
str = "First I. Last, Jr.";

Similar to what @Nasser suggested earlier with slightly different syntax:

{StringTake[str, # - 1],
   StringTake[str, {# + 1, StringLength@str}]
   } &@First@First@StringPosition[str, " "]

If one didn't know about the third argument:

{First@#, StringJoin@Rest@#} &@StringSplit[str, " "]

Using StringCases:

StringCases[str, 
 a : Shortest[___] ~~ " " ~~ b : __ :> Sequence @@ {a, b}]

Circuitous but more flexible:

SequenceReplace[
 Characters@str, {a__, " ", b__} :> 
  Sequence @@ {StringJoin@a, StringJoin@b}]

{"First", "I. Last, Jr."}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.