how to convert a String sentence to arraylist in Kotlin












0















I have this function to convert string sentence to list words. I created this function in Java and converted to Kotlin using default Kotlin conversion in Android Studio, but I believe there can be many ways to shorten this code in Awesome Kotlin. I will be good if you can share your piece of code and help me(and all) to improve our knowledge in Kotlin.



private fun stringToWords(mnemonic: String): List<String> {
val words = ArrayList<String>()
for (word in mnemonic.trim { it <= ' ' }.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
if (word.isNotEmpty()) {
words.add(word)
}
}
return words
}









share|improve this question




















  • 1





    Can you share the original java function as well?

    – Abdul-Aziz-Niazi
    Nov 28 '18 at 5:23











  • gist.github.com/januprasad/8e4f2a8f520e0f8839bbe8e23496ac04

    – januprasad
    Nov 28 '18 at 5:27
















0















I have this function to convert string sentence to list words. I created this function in Java and converted to Kotlin using default Kotlin conversion in Android Studio, but I believe there can be many ways to shorten this code in Awesome Kotlin. I will be good if you can share your piece of code and help me(and all) to improve our knowledge in Kotlin.



private fun stringToWords(mnemonic: String): List<String> {
val words = ArrayList<String>()
for (word in mnemonic.trim { it <= ' ' }.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
if (word.isNotEmpty()) {
words.add(word)
}
}
return words
}









share|improve this question




















  • 1





    Can you share the original java function as well?

    – Abdul-Aziz-Niazi
    Nov 28 '18 at 5:23











  • gist.github.com/januprasad/8e4f2a8f520e0f8839bbe8e23496ac04

    – januprasad
    Nov 28 '18 at 5:27














0












0








0


1






I have this function to convert string sentence to list words. I created this function in Java and converted to Kotlin using default Kotlin conversion in Android Studio, but I believe there can be many ways to shorten this code in Awesome Kotlin. I will be good if you can share your piece of code and help me(and all) to improve our knowledge in Kotlin.



private fun stringToWords(mnemonic: String): List<String> {
val words = ArrayList<String>()
for (word in mnemonic.trim { it <= ' ' }.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
if (word.isNotEmpty()) {
words.add(word)
}
}
return words
}









share|improve this question
















I have this function to convert string sentence to list words. I created this function in Java and converted to Kotlin using default Kotlin conversion in Android Studio, but I believe there can be many ways to shorten this code in Awesome Kotlin. I will be good if you can share your piece of code and help me(and all) to improve our knowledge in Kotlin.



private fun stringToWords(mnemonic: String): List<String> {
val words = ArrayList<String>()
for (word in mnemonic.trim { it <= ' ' }.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
if (word.isNotEmpty()) {
words.add(word)
}
}
return words
}






kotlin






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 '18 at 8:16







januprasad

















asked Nov 28 '18 at 5:15









januprasadjanuprasad

1,5191025




1,5191025








  • 1





    Can you share the original java function as well?

    – Abdul-Aziz-Niazi
    Nov 28 '18 at 5:23











  • gist.github.com/januprasad/8e4f2a8f520e0f8839bbe8e23496ac04

    – januprasad
    Nov 28 '18 at 5:27














  • 1





    Can you share the original java function as well?

    – Abdul-Aziz-Niazi
    Nov 28 '18 at 5:23











  • gist.github.com/januprasad/8e4f2a8f520e0f8839bbe8e23496ac04

    – januprasad
    Nov 28 '18 at 5:27








1




1





Can you share the original java function as well?

– Abdul-Aziz-Niazi
Nov 28 '18 at 5:23





Can you share the original java function as well?

– Abdul-Aziz-Niazi
Nov 28 '18 at 5:23













gist.github.com/januprasad/8e4f2a8f520e0f8839bbe8e23496ac04

– januprasad
Nov 28 '18 at 5:27





gist.github.com/januprasad/8e4f2a8f520e0f8839bbe8e23496ac04

– januprasad
Nov 28 '18 at 5:27












4 Answers
4






active

oldest

votes


















5














I would go for the following:



fun stringToWords(s : String) = s.trim().splitToSequence(' ')
.filter { it.isNotEmpty() } // or: .filter { it.isNotBlank() }
.toList()


Note that you probably want to adjust that filter, e.g. to filter out blank entries too... I put that variant in the comment... (if you use that one, you do not require an initial trim() though)



If you rather want to work with the Sequence you can do so by just omitting the .toList() at the end.



And as also Abdul-Aziz-Niazi said: same is also possible via extension function, if you require it more often:



fun String.toWords() = trim().splitToSequence(' ').filter { it.isNotEmpty() }.toList()





share|improve this answer


























  • I Liked it very much because you're doing in Kotlin Way.

    – januprasad
    Nov 28 '18 at 8:16



















3














It's easier than you think:



fun stringToWords(mnemonic: String) = mnemonic.replace("\s+".toRegex(), " ").trim().split(" ")


Remove multiple spaces, trim start and the end, split.

Like an extention:



fun String.toWords() = replace("\s+".toRegex(), " ").trim().split(" ")


After Roland's suggestion:



fun String.toWords() = trim().split("\s+".toRegex())





share|improve this answer

































    2














    You can do it like this.. Just make a function of return type list.



     val s = "This is a sample sentence."

    val words:Array<String> = s.split("\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    for (i in words.indices) {
    // You may want to check for a non-word character before blindly
    // performing a replacement
    // It may also be necessary to adjust the character class
    words[i] = words[i].replace("[^\w]".toRegex(), "")
    }


    May this will help you :-)






    share|improve this answer































      1














      You don't need scopes, the redundant "".toRegex() and the last expression.
      You can do something like this:



      private fun stringToWords(mnemonic: String): List<String> {
      val words = ArrayList<String>()
      for (w in mnemonic.trim(' ').split(" ")) {
      if (w.isNotEmpty()) {
      words.add(w)
      }
      }
      return words
      }




      Additionally,
      If you use this method a lot in this project, you can make it an extension in string class. Paste this method in a separate file(outside a classes or add it in classless .kt file) so it has a global access.
      and then you can use it with any string like
      myString.toWords() anywhere in the project
      The method will look like this



      inline fun String.toWords(): List<String> {
      val words = ArrayList<String>()
      for (w in this.trim(' ').split(" ")) {
      if (w.isNotEmpty()) {
      words.add(w)
      }
      }
      return words
      }





      share|improve this answer


























      • Yeah, I heard of Extensions. Great Good Answer.

        – januprasad
        Nov 28 '18 at 6:01











      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53512575%2fhow-to-convert-a-string-sentence-to-arraylist-in-kotlin%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      5














      I would go for the following:



      fun stringToWords(s : String) = s.trim().splitToSequence(' ')
      .filter { it.isNotEmpty() } // or: .filter { it.isNotBlank() }
      .toList()


      Note that you probably want to adjust that filter, e.g. to filter out blank entries too... I put that variant in the comment... (if you use that one, you do not require an initial trim() though)



      If you rather want to work with the Sequence you can do so by just omitting the .toList() at the end.



      And as also Abdul-Aziz-Niazi said: same is also possible via extension function, if you require it more often:



      fun String.toWords() = trim().splitToSequence(' ').filter { it.isNotEmpty() }.toList()





      share|improve this answer


























      • I Liked it very much because you're doing in Kotlin Way.

        – januprasad
        Nov 28 '18 at 8:16
















      5














      I would go for the following:



      fun stringToWords(s : String) = s.trim().splitToSequence(' ')
      .filter { it.isNotEmpty() } // or: .filter { it.isNotBlank() }
      .toList()


      Note that you probably want to adjust that filter, e.g. to filter out blank entries too... I put that variant in the comment... (if you use that one, you do not require an initial trim() though)



      If you rather want to work with the Sequence you can do so by just omitting the .toList() at the end.



      And as also Abdul-Aziz-Niazi said: same is also possible via extension function, if you require it more often:



      fun String.toWords() = trim().splitToSequence(' ').filter { it.isNotEmpty() }.toList()





      share|improve this answer


























      • I Liked it very much because you're doing in Kotlin Way.

        – januprasad
        Nov 28 '18 at 8:16














      5












      5








      5







      I would go for the following:



      fun stringToWords(s : String) = s.trim().splitToSequence(' ')
      .filter { it.isNotEmpty() } // or: .filter { it.isNotBlank() }
      .toList()


      Note that you probably want to adjust that filter, e.g. to filter out blank entries too... I put that variant in the comment... (if you use that one, you do not require an initial trim() though)



      If you rather want to work with the Sequence you can do so by just omitting the .toList() at the end.



      And as also Abdul-Aziz-Niazi said: same is also possible via extension function, if you require it more often:



      fun String.toWords() = trim().splitToSequence(' ').filter { it.isNotEmpty() }.toList()





      share|improve this answer















      I would go for the following:



      fun stringToWords(s : String) = s.trim().splitToSequence(' ')
      .filter { it.isNotEmpty() } // or: .filter { it.isNotBlank() }
      .toList()


      Note that you probably want to adjust that filter, e.g. to filter out blank entries too... I put that variant in the comment... (if you use that one, you do not require an initial trim() though)



      If you rather want to work with the Sequence you can do so by just omitting the .toList() at the end.



      And as also Abdul-Aziz-Niazi said: same is also possible via extension function, if you require it more often:



      fun String.toWords() = trim().splitToSequence(' ').filter { it.isNotEmpty() }.toList()






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 28 '18 at 6:30

























      answered Nov 28 '18 at 6:09









      RolandRoland

      10.3k11242




      10.3k11242













      • I Liked it very much because you're doing in Kotlin Way.

        – januprasad
        Nov 28 '18 at 8:16



















      • I Liked it very much because you're doing in Kotlin Way.

        – januprasad
        Nov 28 '18 at 8:16

















      I Liked it very much because you're doing in Kotlin Way.

      – januprasad
      Nov 28 '18 at 8:16





      I Liked it very much because you're doing in Kotlin Way.

      – januprasad
      Nov 28 '18 at 8:16













      3














      It's easier than you think:



      fun stringToWords(mnemonic: String) = mnemonic.replace("\s+".toRegex(), " ").trim().split(" ")


      Remove multiple spaces, trim start and the end, split.

      Like an extention:



      fun String.toWords() = replace("\s+".toRegex(), " ").trim().split(" ")


      After Roland's suggestion:



      fun String.toWords() = trim().split("\s+".toRegex())





      share|improve this answer






























        3














        It's easier than you think:



        fun stringToWords(mnemonic: String) = mnemonic.replace("\s+".toRegex(), " ").trim().split(" ")


        Remove multiple spaces, trim start and the end, split.

        Like an extention:



        fun String.toWords() = replace("\s+".toRegex(), " ").trim().split(" ")


        After Roland's suggestion:



        fun String.toWords() = trim().split("\s+".toRegex())





        share|improve this answer




























          3












          3








          3







          It's easier than you think:



          fun stringToWords(mnemonic: String) = mnemonic.replace("\s+".toRegex(), " ").trim().split(" ")


          Remove multiple spaces, trim start and the end, split.

          Like an extention:



          fun String.toWords() = replace("\s+".toRegex(), " ").trim().split(" ")


          After Roland's suggestion:



          fun String.toWords() = trim().split("\s+".toRegex())





          share|improve this answer















          It's easier than you think:



          fun stringToWords(mnemonic: String) = mnemonic.replace("\s+".toRegex(), " ").trim().split(" ")


          Remove multiple spaces, trim start and the end, split.

          Like an extention:



          fun String.toWords() = replace("\s+".toRegex(), " ").trim().split(" ")


          After Roland's suggestion:



          fun String.toWords() = trim().split("\s+".toRegex())






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 28 '18 at 6:35

























          answered Nov 28 '18 at 6:06









          forpasforpas

          16.8k3628




          16.8k3628























              2














              You can do it like this.. Just make a function of return type list.



               val s = "This is a sample sentence."

              val words:Array<String> = s.split("\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
              for (i in words.indices) {
              // You may want to check for a non-word character before blindly
              // performing a replacement
              // It may also be necessary to adjust the character class
              words[i] = words[i].replace("[^\w]".toRegex(), "")
              }


              May this will help you :-)






              share|improve this answer




























                2














                You can do it like this.. Just make a function of return type list.



                 val s = "This is a sample sentence."

                val words:Array<String> = s.split("\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                for (i in words.indices) {
                // You may want to check for a non-word character before blindly
                // performing a replacement
                // It may also be necessary to adjust the character class
                words[i] = words[i].replace("[^\w]".toRegex(), "")
                }


                May this will help you :-)






                share|improve this answer


























                  2












                  2








                  2







                  You can do it like this.. Just make a function of return type list.



                   val s = "This is a sample sentence."

                  val words:Array<String> = s.split("\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                  for (i in words.indices) {
                  // You may want to check for a non-word character before blindly
                  // performing a replacement
                  // It may also be necessary to adjust the character class
                  words[i] = words[i].replace("[^\w]".toRegex(), "")
                  }


                  May this will help you :-)






                  share|improve this answer













                  You can do it like this.. Just make a function of return type list.



                   val s = "This is a sample sentence."

                  val words:Array<String> = s.split("\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                  for (i in words.indices) {
                  // You may want to check for a non-word character before blindly
                  // performing a replacement
                  // It may also be necessary to adjust the character class
                  words[i] = words[i].replace("[^\w]".toRegex(), "")
                  }


                  May this will help you :-)







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 28 '18 at 6:16









                  Shivesh Karan MehtaShivesh Karan Mehta

                  235




                  235























                      1














                      You don't need scopes, the redundant "".toRegex() and the last expression.
                      You can do something like this:



                      private fun stringToWords(mnemonic: String): List<String> {
                      val words = ArrayList<String>()
                      for (w in mnemonic.trim(' ').split(" ")) {
                      if (w.isNotEmpty()) {
                      words.add(w)
                      }
                      }
                      return words
                      }




                      Additionally,
                      If you use this method a lot in this project, you can make it an extension in string class. Paste this method in a separate file(outside a classes or add it in classless .kt file) so it has a global access.
                      and then you can use it with any string like
                      myString.toWords() anywhere in the project
                      The method will look like this



                      inline fun String.toWords(): List<String> {
                      val words = ArrayList<String>()
                      for (w in this.trim(' ').split(" ")) {
                      if (w.isNotEmpty()) {
                      words.add(w)
                      }
                      }
                      return words
                      }





                      share|improve this answer


























                      • Yeah, I heard of Extensions. Great Good Answer.

                        – januprasad
                        Nov 28 '18 at 6:01
















                      1














                      You don't need scopes, the redundant "".toRegex() and the last expression.
                      You can do something like this:



                      private fun stringToWords(mnemonic: String): List<String> {
                      val words = ArrayList<String>()
                      for (w in mnemonic.trim(' ').split(" ")) {
                      if (w.isNotEmpty()) {
                      words.add(w)
                      }
                      }
                      return words
                      }




                      Additionally,
                      If you use this method a lot in this project, you can make it an extension in string class. Paste this method in a separate file(outside a classes or add it in classless .kt file) so it has a global access.
                      and then you can use it with any string like
                      myString.toWords() anywhere in the project
                      The method will look like this



                      inline fun String.toWords(): List<String> {
                      val words = ArrayList<String>()
                      for (w in this.trim(' ').split(" ")) {
                      if (w.isNotEmpty()) {
                      words.add(w)
                      }
                      }
                      return words
                      }





                      share|improve this answer


























                      • Yeah, I heard of Extensions. Great Good Answer.

                        – januprasad
                        Nov 28 '18 at 6:01














                      1












                      1








                      1







                      You don't need scopes, the redundant "".toRegex() and the last expression.
                      You can do something like this:



                      private fun stringToWords(mnemonic: String): List<String> {
                      val words = ArrayList<String>()
                      for (w in mnemonic.trim(' ').split(" ")) {
                      if (w.isNotEmpty()) {
                      words.add(w)
                      }
                      }
                      return words
                      }




                      Additionally,
                      If you use this method a lot in this project, you can make it an extension in string class. Paste this method in a separate file(outside a classes or add it in classless .kt file) so it has a global access.
                      and then you can use it with any string like
                      myString.toWords() anywhere in the project
                      The method will look like this



                      inline fun String.toWords(): List<String> {
                      val words = ArrayList<String>()
                      for (w in this.trim(' ').split(" ")) {
                      if (w.isNotEmpty()) {
                      words.add(w)
                      }
                      }
                      return words
                      }





                      share|improve this answer















                      You don't need scopes, the redundant "".toRegex() and the last expression.
                      You can do something like this:



                      private fun stringToWords(mnemonic: String): List<String> {
                      val words = ArrayList<String>()
                      for (w in mnemonic.trim(' ').split(" ")) {
                      if (w.isNotEmpty()) {
                      words.add(w)
                      }
                      }
                      return words
                      }




                      Additionally,
                      If you use this method a lot in this project, you can make it an extension in string class. Paste this method in a separate file(outside a classes or add it in classless .kt file) so it has a global access.
                      and then you can use it with any string like
                      myString.toWords() anywhere in the project
                      The method will look like this



                      inline fun String.toWords(): List<String> {
                      val words = ArrayList<String>()
                      for (w in this.trim(' ').split(" ")) {
                      if (w.isNotEmpty()) {
                      words.add(w)
                      }
                      }
                      return words
                      }






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 28 '18 at 6:14









                      januprasad

                      1,5191025




                      1,5191025










                      answered Nov 28 '18 at 5:38









                      Abdul-Aziz-NiaziAbdul-Aziz-Niazi

                      955818




                      955818













                      • Yeah, I heard of Extensions. Great Good Answer.

                        – januprasad
                        Nov 28 '18 at 6:01



















                      • Yeah, I heard of Extensions. Great Good Answer.

                        – januprasad
                        Nov 28 '18 at 6:01

















                      Yeah, I heard of Extensions. Great Good Answer.

                      – januprasad
                      Nov 28 '18 at 6:01





                      Yeah, I heard of Extensions. Great Good Answer.

                      – januprasad
                      Nov 28 '18 at 6:01


















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53512575%2fhow-to-convert-a-string-sentence-to-arraylist-in-kotlin%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                      Calculate evaluation metrics using cross_val_predict sklearn

                      Insert data from modal to MySQL (multiple modal on website)