{"id":2423,"date":"2022-04-18T14:06:36","date_gmt":"2022-04-18T19:06:36","guid":{"rendered":"http:\/\/www.becomebetterprogrammer.com\/staging\/4563\/?p=2423"},"modified":"2022-04-23T12:53:14","modified_gmt":"2022-04-23T17:53:14","slug":"split-string-rust","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/split-string-rust\/","title":{"rendered":"How to Split a String in Rust? (Explained with Examples)"},"content":{"rendered":"\n<p>Regardless of the programming language, splitting a string is a common practice that programmers, developers, and software engineers will have to do at some point during their careers. In this article, we are going to explain how to split a string using Rust programming language, and the different alternatives available.<\/p>\n\n\n\n<p><strong>Note<\/strong>: While the main question is to split a string in Rust, this article presents different ways to split string slices. <a href=\"https:\/\/www.becomebetterprogrammer.com\/rust-string-vs-str\/\" target=\"_blank\" rel=\"noreferrer noopener\">Do not confuse a string with a string slice<\/a>.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/split-string-rust\/#How_to_Split_a_String_Slice_Using_the_split_Method\" >How to Split a String Slice Using the split() Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/split-string-rust\/#How_to_Split_a_String_Slice_Using_the_split_whitespace_Method\" >How to Split a String Slice Using the split_whitespace() Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/split-string-rust\/#How_to_Split_a_String_Slice_Using_the_split_terminator_Method\" >How to Split a String Slice Using the split_terminator() Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/split-string-rust\/#How_to_Generate_a_Growable_Array_After_Splitting_a_String_Slice\" >How to Generate a Growable Array After Splitting a String Slice<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/split-string-rust\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_to_Split_a_String_Slice_Using_the_split_Method\"><\/span>How to Split a String Slice Using the split() Method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong>To split a string slice or type <code>&amp;str<\/code> in Rust, use <a href=\"https:\/\/doc.rust-lang.org\/std\/primitive.str.html#method.split\" target=\"_blank\" rel=\"noreferrer noopener\">the split() method<\/a> to create an <a href=\"https:\/\/doc.rust-lang.org\/std\/iter\/trait.Iterator.html\" target=\"_blank\" rel=\"noreferrer noopener\">iterator<\/a>. Once the iterator is generated, use a <code>for<\/code> loop to access each substring to apply any additional business logic<\/strong>. Let&#8217;s look at this implementation in the following snippet of code. <\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>use std::str::Split;\n\nfn main() {\n    let text: &amp;str = \"Manchester Bogota Paris Dallas Chicago\";\n    let cities: Split&lt;&amp;str&gt; = text.split(\" \");\n\n    for city in cities {\n        println!(\"City {}\", city);        \n    }\n}\n\n\/\/ or\n \nfn main() {\n    let cities: Split&lt;&amp;str&gt; = \"Manchester Bogota Paris Dallas Chicago\".split(\" \");\n\n    for city in cities {\n        println!(\"City {}\", city);        \n    }\n}\n\n\/\/ Output\n\/\/ City Manchester\n\/\/ City Bogota\n\/\/ City Paris\n\/\/ City Dallas\n\/\/ City Chicago<\/code><\/pre>\n\n\n\n<p>Notice how we logged each city after splitting them by a space character <code>\" \"<\/code>. The split() method can accept another separator as an argument besides the space character. For instance, we could extract the sentences of a paragraph by separating them with a period<code>\".\"<\/code> .<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n   let paragraphs = \"Lorem ipsum dolor. Ut enim ad minim veniam. Duis aute irure . Excepteur sint.\".split(\".\");\n\n    for paragraph in paragraphs {\n        println!(\"Paragraph {}\", paragraph);        \n    }\n}\n\n\/\/ Output\n\/\/ Paragraph Lorem ipsum dolor\n\/\/ Paragraph  Ut enim ad minim veniam\n\/\/ Paragraph  Duis aute irure\n\/\/ Paragraph  Excepteur sint\n\/\/ Paragraph<\/code><\/pre>\n\n\n\n<p>Unfortunately, the last example would introduce a logical error as it displays an empty string for the last element. To quickly fix this, check for empty strings by leveraging the <a href=\"https:\/\/doc.rust-lang.org\/std\/primitive.str.html#method.is_empty\" target=\"_blank\" rel=\"noreferrer noopener\">is_empty() method<\/a> on the string slice <code>paragraph<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n    let paragraphs =\n        \"Lorem ipsum dolor. Ut enim ad minim veniam. Duis aute irure . Excepteur sint.\".split(\".\");\n\n    for paragraph in paragraphs {\n        if (!paragraph.is_empty()) {\n            println!(\"Paragraph {}\", paragraph);\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_to_Split_a_String_Slice_Using_the_split_whitespace_Method\"><\/span>How to Split a String Slice Using the split_whitespace() Method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In the previous example, we used the split() method to split a string slice separated by spaces. Rust provides a built-in method that does the same, without the need of passing whitespace as a parameter, called <a href=\"https:\/\/doc.rust-lang.org\/std\/primitive.str.html#method.split_whitespace\" target=\"_blank\" rel=\"noreferrer noopener\">split_whitespace()<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>use std::str::SplitWhitespace;\n\nfn main() {\n    let cities: SplitWhitespace = \"Manchester Bogota Paris Dallas Chicago\".split_whitespace();\n\n    for city in cities {\n        println!(\"City {}\", city);        \n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Note<\/strong>: In case you decide to update from using the split() method to using the split_whitespace() method, make sure to also update the type of the variable, in our case <code>cities<\/code> to <code>SplitWhiteSpace<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_to_Split_a_String_Slice_Using_the_split_terminator_Method\"><\/span>How to Split a String Slice Using the split_terminator() Method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Remember when we used the split() method to split sentences in a paragraph? We had to apply additional logic to check for empty substrings after using the split method. This is what the solution looked like.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n    let paragraphs =\n        \"Lorem ipsum dolor. Ut enim ad minim veniam. Duis aute irure . Excepteur sint.\".split(\".\");\n\n    for paragraph in paragraphs {\n        if (!paragraph.is_empty()) {\n            println!(\"Paragraph {}\", paragraph);\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p>Notice how it checks whether the substring <code>paragraph<\/code> is empty prior to printing it in the terminal. We can avoid this check by using the <a href=\"https:\/\/doc.rust-lang.org\/std\/primitive.str.html#method.split_terminator\" target=\"_blank\" rel=\"noreferrer noopener\">split_terminator() method<\/a> instead of the split() method.<\/p>\n\n\n\n<p><strong>The split_terminator() method is the equivalent to the split method, except that substrings are skipped if they are empty.<\/strong> Hence, by using the split_terminator() method, we no longer have to check for empty strings. Let&#8217;s look at the new implementation of the code.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n    let paragraphs =\n        \"Lorem ipsum dolor. Ut enim ad minim veniam. Duis aute irure . Excepteur sint.\".split_terminator(\".\");\n\n    for paragraph in paragraphs {\n        println!(\"Paragraph {}\", paragraph);\n    }\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_to_Generate_a_Growable_Array_After_Splitting_a_String_Slice\"><\/span>How to Generate a Growable Array After Splitting a String Slice<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In case you don&#8217;t want to use a <code>for<\/code> loop, but instead, generate a collection or a <a href=\"https:\/\/doc.rust-lang.org\/std\/vec\/struct.Vec.html\" target=\"_blank\" rel=\"noreferrer noopener\">growable array<\/a> (<code>Vec&lt;&amp;str&gt;<\/code>), apply the split() method on the string slice followed by <a href=\"https:\/\/doc.rust-lang.org\/std\/iter\/trait.Iterator.html#method.collect\" target=\"_blank\" rel=\"noreferrer noopener\">the collect() method<\/a> once the iterator is generated.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n    let text: &amp;str = \"Manchester Bogota Paris Dallas Chicago\";\n    let cities: Split&lt;&amp;str&gt; = text.split(\" \");\n    let array_cities: Vec&lt;&amp;str&gt; = cities.collect();\n}\n\n\/\/ or\n\nfn main() {\n   let array_cities: Vec&lt;&amp;str&gt; = \"Manchester Bogota Paris Dallas Chicago\"\n        .split(\" \")\n        .collect();\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>While it is common to use the split() method to split a string slice, there are other built-in methods available that already simplify the job such as using split_whitespace(), in case we split by whitespace, or using the split_terminator(), in case we want to skip empty substrings.<\/p>\n\n\n\n<p><strong>Was this article helpful?<\/strong><\/p>\n\n\n\n<p>I hope this article helped you find a definite answer to such a common task as splitting a string in Rust.<\/p>\n\n\n\n<p>Share your thoughts by replying on <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noreferrer noopener\">Twitter of Become A Better Programmer<\/a> or to <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noreferrer noopener\">my personal Twitter account<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Regardless of the programming language, splitting a string is a common practice that programmers, developers, and software engineers will have to do at some point during their careers. In this article, we are going to explain how to split a string using Rust programming language, and the different alternatives available. Note: While the main question &#8230; <a title=\"How to Split a String in Rust? (Explained with Examples)\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/split-string-rust\/\" aria-label=\"More on How to Split a String in Rust? (Explained with Examples)\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":2428,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[31],"tags":[],"class_list":["post-2423","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-rust","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2423","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=2423"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2423\/revisions"}],"predecessor-version":[{"id":2444,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2423\/revisions\/2444"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/2428"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=2423"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=2423"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=2423"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}