Getting the lengths of each word in its String parameter











up vote
6
down vote

favorite












Is this a smart method?



public static ArrayList<Integer> getWordLengths( String s )
{

String str = " " + s + " ";

ArrayList<Integer> list = new ArrayList<Integer>();

for ( int i = 0; i < str.length(); i++ )
{
if ( str.charAt(i) == ' ' )
{
for ( int j = i+1; j < str.length() ; j++)
{
if ( str.charAt(j) == ' ')
{
list.add( j - i - 1 );
j = str.length();
}
}
}
}
return list;
}


Sample output:





System.out.println( getWordLengths("This is really easy")); 

[4, 2, 6, 4]


so it worked.



We are only allowed to use length and charAt from the String class.










share|improve this question















migrated from stackoverflow.com Dec 24 '14 at 3:36


This question came from our site for professional and enthusiast programmers.















  • Something I'm seeing: all solutions would fail with "This_is__not__so_easy" (_ are spaces). That is simply fixed by adding if (s.charAt(i) == ' ' && count > 0) { ...
    – Santiago
    Dec 24 '14 at 6:09

















up vote
6
down vote

favorite












Is this a smart method?



public static ArrayList<Integer> getWordLengths( String s )
{

String str = " " + s + " ";

ArrayList<Integer> list = new ArrayList<Integer>();

for ( int i = 0; i < str.length(); i++ )
{
if ( str.charAt(i) == ' ' )
{
for ( int j = i+1; j < str.length() ; j++)
{
if ( str.charAt(j) == ' ')
{
list.add( j - i - 1 );
j = str.length();
}
}
}
}
return list;
}


Sample output:





System.out.println( getWordLengths("This is really easy")); 

[4, 2, 6, 4]


so it worked.



We are only allowed to use length and charAt from the String class.










share|improve this question















migrated from stackoverflow.com Dec 24 '14 at 3:36


This question came from our site for professional and enthusiast programmers.















  • Something I'm seeing: all solutions would fail with "This_is__not__so_easy" (_ are spaces). That is simply fixed by adding if (s.charAt(i) == ' ' && count > 0) { ...
    – Santiago
    Dec 24 '14 at 6:09















up vote
6
down vote

favorite









up vote
6
down vote

favorite











Is this a smart method?



public static ArrayList<Integer> getWordLengths( String s )
{

String str = " " + s + " ";

ArrayList<Integer> list = new ArrayList<Integer>();

for ( int i = 0; i < str.length(); i++ )
{
if ( str.charAt(i) == ' ' )
{
for ( int j = i+1; j < str.length() ; j++)
{
if ( str.charAt(j) == ' ')
{
list.add( j - i - 1 );
j = str.length();
}
}
}
}
return list;
}


Sample output:





System.out.println( getWordLengths("This is really easy")); 

[4, 2, 6, 4]


so it worked.



We are only allowed to use length and charAt from the String class.










share|improve this question















Is this a smart method?



public static ArrayList<Integer> getWordLengths( String s )
{

String str = " " + s + " ";

ArrayList<Integer> list = new ArrayList<Integer>();

for ( int i = 0; i < str.length(); i++ )
{
if ( str.charAt(i) == ' ' )
{
for ( int j = i+1; j < str.length() ; j++)
{
if ( str.charAt(j) == ' ')
{
list.add( j - i - 1 );
j = str.length();
}
}
}
}
return list;
}


Sample output:





System.out.println( getWordLengths("This is really easy")); 

[4, 2, 6, 4]


so it worked.



We are only allowed to use length and charAt from the String class.







java strings






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 24 '14 at 3:53









Jamal

30.2k11115226




30.2k11115226










asked Dec 24 '14 at 3:09









funky-nd

104128




104128




migrated from stackoverflow.com Dec 24 '14 at 3:36


This question came from our site for professional and enthusiast programmers.






migrated from stackoverflow.com Dec 24 '14 at 3:36


This question came from our site for professional and enthusiast programmers.














  • Something I'm seeing: all solutions would fail with "This_is__not__so_easy" (_ are spaces). That is simply fixed by adding if (s.charAt(i) == ' ' && count > 0) { ...
    – Santiago
    Dec 24 '14 at 6:09




















  • Something I'm seeing: all solutions would fail with "This_is__not__so_easy" (_ are spaces). That is simply fixed by adding if (s.charAt(i) == ' ' && count > 0) { ...
    – Santiago
    Dec 24 '14 at 6:09


















Something I'm seeing: all solutions would fail with "This_is__not__so_easy" (_ are spaces). That is simply fixed by adding if (s.charAt(i) == ' ' && count > 0) { ...
– Santiago
Dec 24 '14 at 6:09






Something I'm seeing: all solutions would fail with "This_is__not__so_easy" (_ are spaces). That is simply fixed by adding if (s.charAt(i) == ' ' && count > 0) { ...
– Santiago
Dec 24 '14 at 6:09












4 Answers
4






active

oldest

votes

















up vote
1
down vote



accepted










Code:



    String s = "This is really easy";

int count = 0;

for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
System.out.println("count is " + count);
count = 0;
} else {
count++;
}
}
System.out.println("count is " + count);


Output:



count is 4
count is 2
count is 6
count is 4


Explanation:



keep counting the length of each word till you see a blank. As soon as, you see a blank, write down a length current word and set count to zero and make it ready for new word. At the end, you should write down the length the last word outside of the for loop.



Note: Big o of my code is n , yet your is n^2; therefore, my method is faster than your approach.






share|improve this answer





















  • Does not produce the requested output. For a trivial fix consider System.out.print(count + ", ");
    – candied_orange
    Dec 24 '14 at 8:25


















up vote
2
down vote













//only allowed to use length and charAt from string class
public static ArrayList<Integer> getWordLengths( String s )
{
String str = s + " ";

ArrayList<Integer> list = new ArrayList<Integer>();

int count = 0;

for ( int i = 0; i < str.length(); i++ )
{
if ( str.charAt(i) == ' ' )
{
list.add(count);
count = 0;
}
else
{
count++;
}
}
return list;
}


Output:



[4, 2, 6, 4]


As long as the length and charAt limitations only apply to string methods and not to use of a List this should be fine. Just because you need to count more than one thing doesn't mean you need more than one loop.






share|improve this answer























  • Thanks it worked for me.
    – supriya mishra
    Nov 21 at 12:49


















up vote
1
down vote













There is a split method for String that will split your string into an array of Strings based on the value you give it.



So in this case you could use spaces:



String arr = s.split(" ");
int result = arr.length;
for(int x = 0; x < arr.length; x++) {
result[x] = arr[x].length();
}


Since you can only use length and charAt, you could also do it this way, which is faster. list will contain the lengths of each word. prev keeps track of the start of the word you're on, so you can use it to subtract when you find the next space. You have to add 1 to it each time so that it will be on the beginning of the word instead of the space.



ArrayList<Integer> list = new ArrayList<Integer>();
int prev = 0;
for(int x = 0; x <= line.length(); x++) {
if(x == line.length() || line.charAt(x) == ' ') {
list.add(x - prev);
prev = x + 1;
}
}


Check out the String class API! If you want to look into split more, here are some good examples!






share|improve this answer



















  • 1




    thank you, it is nice.. but there is a note: we are only allowed to use charAt and length method from string class :(
    – cihangir ND
    Dec 24 '14 at 3:19










  • @haley if you clarify "different parts based on what you tell it." better, I gladly vote u up
    – Kick Buttowski
    Dec 24 '14 at 3:21










  • @KickButtowski I'll do that!
    – haley
    Dec 24 '14 at 3:27






  • 1




    @cihangirND let me know if the edit I made helps! :)
    – haley
    Dec 24 '14 at 3:33






  • 1




    Sorry about that! I changed the for loop to go <= to the length and I added a condition to the if statement. This won't cause an index out of bounds because the if statement will short circuit before it tries to get the character at line.length().
    – haley
    Dec 24 '14 at 3:54


















up vote
1
down vote













If you aren't allowed to use ArrayList, or if you just think tail recursion is cool, you can do it this way:



public static void main(String args) {

System.out.println( getWordLengths("This is really easy") );
}

public static String getWordLengths( String s )
{
return "[" + getWordLengthsRecursively(s, 0, 0, 0) + "]";
}

public static String getWordLengthsRecursively( String s, int i, int start, int end )
{
// Last word
if ( s.length() == i)
{
return "" + (end - start);
}

// Found a word
if ( s.charAt(i) == ' ' )
{
return (end - start) + ", " + getWordLengthsRecursively(s, ++i, i, i);
}

// Word not found. Move to next character.
else
{
return getWordLengthsRecursively(s, ++i, start, ++end);
}
}


Output:



[4, 2, 6, 4]


I like it when I don't have to import anything. Don't you?






share|improve this answer























    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    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: "196"
    };
    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',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    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%2fcodereview.stackexchange.com%2fquestions%2f74722%2fgetting-the-lengths-of-each-word-in-its-string-parameter%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








    up vote
    1
    down vote



    accepted










    Code:



        String s = "This is really easy";

    int count = 0;

    for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == ' ') {
    System.out.println("count is " + count);
    count = 0;
    } else {
    count++;
    }
    }
    System.out.println("count is " + count);


    Output:



    count is 4
    count is 2
    count is 6
    count is 4


    Explanation:



    keep counting the length of each word till you see a blank. As soon as, you see a blank, write down a length current word and set count to zero and make it ready for new word. At the end, you should write down the length the last word outside of the for loop.



    Note: Big o of my code is n , yet your is n^2; therefore, my method is faster than your approach.






    share|improve this answer





















    • Does not produce the requested output. For a trivial fix consider System.out.print(count + ", ");
      – candied_orange
      Dec 24 '14 at 8:25















    up vote
    1
    down vote



    accepted










    Code:



        String s = "This is really easy";

    int count = 0;

    for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == ' ') {
    System.out.println("count is " + count);
    count = 0;
    } else {
    count++;
    }
    }
    System.out.println("count is " + count);


    Output:



    count is 4
    count is 2
    count is 6
    count is 4


    Explanation:



    keep counting the length of each word till you see a blank. As soon as, you see a blank, write down a length current word and set count to zero and make it ready for new word. At the end, you should write down the length the last word outside of the for loop.



    Note: Big o of my code is n , yet your is n^2; therefore, my method is faster than your approach.






    share|improve this answer





















    • Does not produce the requested output. For a trivial fix consider System.out.print(count + ", ");
      – candied_orange
      Dec 24 '14 at 8:25













    up vote
    1
    down vote



    accepted







    up vote
    1
    down vote



    accepted






    Code:



        String s = "This is really easy";

    int count = 0;

    for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == ' ') {
    System.out.println("count is " + count);
    count = 0;
    } else {
    count++;
    }
    }
    System.out.println("count is " + count);


    Output:



    count is 4
    count is 2
    count is 6
    count is 4


    Explanation:



    keep counting the length of each word till you see a blank. As soon as, you see a blank, write down a length current word and set count to zero and make it ready for new word. At the end, you should write down the length the last word outside of the for loop.



    Note: Big o of my code is n , yet your is n^2; therefore, my method is faster than your approach.






    share|improve this answer












    Code:



        String s = "This is really easy";

    int count = 0;

    for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == ' ') {
    System.out.println("count is " + count);
    count = 0;
    } else {
    count++;
    }
    }
    System.out.println("count is " + count);


    Output:



    count is 4
    count is 2
    count is 6
    count is 4


    Explanation:



    keep counting the length of each word till you see a blank. As soon as, you see a blank, write down a length current word and set count to zero and make it ready for new word. At the end, you should write down the length the last word outside of the for loop.



    Note: Big o of my code is n , yet your is n^2; therefore, my method is faster than your approach.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Dec 24 '14 at 3:32







    Kick Buttowski



















    • Does not produce the requested output. For a trivial fix consider System.out.print(count + ", ");
      – candied_orange
      Dec 24 '14 at 8:25


















    • Does not produce the requested output. For a trivial fix consider System.out.print(count + ", ");
      – candied_orange
      Dec 24 '14 at 8:25
















    Does not produce the requested output. For a trivial fix consider System.out.print(count + ", ");
    – candied_orange
    Dec 24 '14 at 8:25




    Does not produce the requested output. For a trivial fix consider System.out.print(count + ", ");
    – candied_orange
    Dec 24 '14 at 8:25












    up vote
    2
    down vote













    //only allowed to use length and charAt from string class
    public static ArrayList<Integer> getWordLengths( String s )
    {
    String str = s + " ";

    ArrayList<Integer> list = new ArrayList<Integer>();

    int count = 0;

    for ( int i = 0; i < str.length(); i++ )
    {
    if ( str.charAt(i) == ' ' )
    {
    list.add(count);
    count = 0;
    }
    else
    {
    count++;
    }
    }
    return list;
    }


    Output:



    [4, 2, 6, 4]


    As long as the length and charAt limitations only apply to string methods and not to use of a List this should be fine. Just because you need to count more than one thing doesn't mean you need more than one loop.






    share|improve this answer























    • Thanks it worked for me.
      – supriya mishra
      Nov 21 at 12:49















    up vote
    2
    down vote













    //only allowed to use length and charAt from string class
    public static ArrayList<Integer> getWordLengths( String s )
    {
    String str = s + " ";

    ArrayList<Integer> list = new ArrayList<Integer>();

    int count = 0;

    for ( int i = 0; i < str.length(); i++ )
    {
    if ( str.charAt(i) == ' ' )
    {
    list.add(count);
    count = 0;
    }
    else
    {
    count++;
    }
    }
    return list;
    }


    Output:



    [4, 2, 6, 4]


    As long as the length and charAt limitations only apply to string methods and not to use of a List this should be fine. Just because you need to count more than one thing doesn't mean you need more than one loop.






    share|improve this answer























    • Thanks it worked for me.
      – supriya mishra
      Nov 21 at 12:49













    up vote
    2
    down vote










    up vote
    2
    down vote









    //only allowed to use length and charAt from string class
    public static ArrayList<Integer> getWordLengths( String s )
    {
    String str = s + " ";

    ArrayList<Integer> list = new ArrayList<Integer>();

    int count = 0;

    for ( int i = 0; i < str.length(); i++ )
    {
    if ( str.charAt(i) == ' ' )
    {
    list.add(count);
    count = 0;
    }
    else
    {
    count++;
    }
    }
    return list;
    }


    Output:



    [4, 2, 6, 4]


    As long as the length and charAt limitations only apply to string methods and not to use of a List this should be fine. Just because you need to count more than one thing doesn't mean you need more than one loop.






    share|improve this answer














    //only allowed to use length and charAt from string class
    public static ArrayList<Integer> getWordLengths( String s )
    {
    String str = s + " ";

    ArrayList<Integer> list = new ArrayList<Integer>();

    int count = 0;

    for ( int i = 0; i < str.length(); i++ )
    {
    if ( str.charAt(i) == ' ' )
    {
    list.add(count);
    count = 0;
    }
    else
    {
    count++;
    }
    }
    return list;
    }


    Output:



    [4, 2, 6, 4]


    As long as the length and charAt limitations only apply to string methods and not to use of a List this should be fine. Just because you need to count more than one thing doesn't mean you need more than one loop.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 21 at 13:24

























    answered Dec 24 '14 at 3:43









    candied_orange

    387219




    387219












    • Thanks it worked for me.
      – supriya mishra
      Nov 21 at 12:49


















    • Thanks it worked for me.
      – supriya mishra
      Nov 21 at 12:49
















    Thanks it worked for me.
    – supriya mishra
    Nov 21 at 12:49




    Thanks it worked for me.
    – supriya mishra
    Nov 21 at 12:49










    up vote
    1
    down vote













    There is a split method for String that will split your string into an array of Strings based on the value you give it.



    So in this case you could use spaces:



    String arr = s.split(" ");
    int result = arr.length;
    for(int x = 0; x < arr.length; x++) {
    result[x] = arr[x].length();
    }


    Since you can only use length and charAt, you could also do it this way, which is faster. list will contain the lengths of each word. prev keeps track of the start of the word you're on, so you can use it to subtract when you find the next space. You have to add 1 to it each time so that it will be on the beginning of the word instead of the space.



    ArrayList<Integer> list = new ArrayList<Integer>();
    int prev = 0;
    for(int x = 0; x <= line.length(); x++) {
    if(x == line.length() || line.charAt(x) == ' ') {
    list.add(x - prev);
    prev = x + 1;
    }
    }


    Check out the String class API! If you want to look into split more, here are some good examples!






    share|improve this answer



















    • 1




      thank you, it is nice.. but there is a note: we are only allowed to use charAt and length method from string class :(
      – cihangir ND
      Dec 24 '14 at 3:19










    • @haley if you clarify "different parts based on what you tell it." better, I gladly vote u up
      – Kick Buttowski
      Dec 24 '14 at 3:21










    • @KickButtowski I'll do that!
      – haley
      Dec 24 '14 at 3:27






    • 1




      @cihangirND let me know if the edit I made helps! :)
      – haley
      Dec 24 '14 at 3:33






    • 1




      Sorry about that! I changed the for loop to go <= to the length and I added a condition to the if statement. This won't cause an index out of bounds because the if statement will short circuit before it tries to get the character at line.length().
      – haley
      Dec 24 '14 at 3:54















    up vote
    1
    down vote













    There is a split method for String that will split your string into an array of Strings based on the value you give it.



    So in this case you could use spaces:



    String arr = s.split(" ");
    int result = arr.length;
    for(int x = 0; x < arr.length; x++) {
    result[x] = arr[x].length();
    }


    Since you can only use length and charAt, you could also do it this way, which is faster. list will contain the lengths of each word. prev keeps track of the start of the word you're on, so you can use it to subtract when you find the next space. You have to add 1 to it each time so that it will be on the beginning of the word instead of the space.



    ArrayList<Integer> list = new ArrayList<Integer>();
    int prev = 0;
    for(int x = 0; x <= line.length(); x++) {
    if(x == line.length() || line.charAt(x) == ' ') {
    list.add(x - prev);
    prev = x + 1;
    }
    }


    Check out the String class API! If you want to look into split more, here are some good examples!






    share|improve this answer



















    • 1




      thank you, it is nice.. but there is a note: we are only allowed to use charAt and length method from string class :(
      – cihangir ND
      Dec 24 '14 at 3:19










    • @haley if you clarify "different parts based on what you tell it." better, I gladly vote u up
      – Kick Buttowski
      Dec 24 '14 at 3:21










    • @KickButtowski I'll do that!
      – haley
      Dec 24 '14 at 3:27






    • 1




      @cihangirND let me know if the edit I made helps! :)
      – haley
      Dec 24 '14 at 3:33






    • 1




      Sorry about that! I changed the for loop to go <= to the length and I added a condition to the if statement. This won't cause an index out of bounds because the if statement will short circuit before it tries to get the character at line.length().
      – haley
      Dec 24 '14 at 3:54













    up vote
    1
    down vote










    up vote
    1
    down vote









    There is a split method for String that will split your string into an array of Strings based on the value you give it.



    So in this case you could use spaces:



    String arr = s.split(" ");
    int result = arr.length;
    for(int x = 0; x < arr.length; x++) {
    result[x] = arr[x].length();
    }


    Since you can only use length and charAt, you could also do it this way, which is faster. list will contain the lengths of each word. prev keeps track of the start of the word you're on, so you can use it to subtract when you find the next space. You have to add 1 to it each time so that it will be on the beginning of the word instead of the space.



    ArrayList<Integer> list = new ArrayList<Integer>();
    int prev = 0;
    for(int x = 0; x <= line.length(); x++) {
    if(x == line.length() || line.charAt(x) == ' ') {
    list.add(x - prev);
    prev = x + 1;
    }
    }


    Check out the String class API! If you want to look into split more, here are some good examples!






    share|improve this answer














    There is a split method for String that will split your string into an array of Strings based on the value you give it.



    So in this case you could use spaces:



    String arr = s.split(" ");
    int result = arr.length;
    for(int x = 0; x < arr.length; x++) {
    result[x] = arr[x].length();
    }


    Since you can only use length and charAt, you could also do it this way, which is faster. list will contain the lengths of each word. prev keeps track of the start of the word you're on, so you can use it to subtract when you find the next space. You have to add 1 to it each time so that it will be on the beginning of the word instead of the space.



    ArrayList<Integer> list = new ArrayList<Integer>();
    int prev = 0;
    for(int x = 0; x <= line.length(); x++) {
    if(x == line.length() || line.charAt(x) == ' ') {
    list.add(x - prev);
    prev = x + 1;
    }
    }


    Check out the String class API! If you want to look into split more, here are some good examples!







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Dec 24 '14 at 3:57









    Jamal

    30.2k11115226




    30.2k11115226










    answered Dec 24 '14 at 3:15









    haley

    1113




    1113








    • 1




      thank you, it is nice.. but there is a note: we are only allowed to use charAt and length method from string class :(
      – cihangir ND
      Dec 24 '14 at 3:19










    • @haley if you clarify "different parts based on what you tell it." better, I gladly vote u up
      – Kick Buttowski
      Dec 24 '14 at 3:21










    • @KickButtowski I'll do that!
      – haley
      Dec 24 '14 at 3:27






    • 1




      @cihangirND let me know if the edit I made helps! :)
      – haley
      Dec 24 '14 at 3:33






    • 1




      Sorry about that! I changed the for loop to go <= to the length and I added a condition to the if statement. This won't cause an index out of bounds because the if statement will short circuit before it tries to get the character at line.length().
      – haley
      Dec 24 '14 at 3:54














    • 1




      thank you, it is nice.. but there is a note: we are only allowed to use charAt and length method from string class :(
      – cihangir ND
      Dec 24 '14 at 3:19










    • @haley if you clarify "different parts based on what you tell it." better, I gladly vote u up
      – Kick Buttowski
      Dec 24 '14 at 3:21










    • @KickButtowski I'll do that!
      – haley
      Dec 24 '14 at 3:27






    • 1




      @cihangirND let me know if the edit I made helps! :)
      – haley
      Dec 24 '14 at 3:33






    • 1




      Sorry about that! I changed the for loop to go <= to the length and I added a condition to the if statement. This won't cause an index out of bounds because the if statement will short circuit before it tries to get the character at line.length().
      – haley
      Dec 24 '14 at 3:54








    1




    1




    thank you, it is nice.. but there is a note: we are only allowed to use charAt and length method from string class :(
    – cihangir ND
    Dec 24 '14 at 3:19




    thank you, it is nice.. but there is a note: we are only allowed to use charAt and length method from string class :(
    – cihangir ND
    Dec 24 '14 at 3:19












    @haley if you clarify "different parts based on what you tell it." better, I gladly vote u up
    – Kick Buttowski
    Dec 24 '14 at 3:21




    @haley if you clarify "different parts based on what you tell it." better, I gladly vote u up
    – Kick Buttowski
    Dec 24 '14 at 3:21












    @KickButtowski I'll do that!
    – haley
    Dec 24 '14 at 3:27




    @KickButtowski I'll do that!
    – haley
    Dec 24 '14 at 3:27




    1




    1




    @cihangirND let me know if the edit I made helps! :)
    – haley
    Dec 24 '14 at 3:33




    @cihangirND let me know if the edit I made helps! :)
    – haley
    Dec 24 '14 at 3:33




    1




    1




    Sorry about that! I changed the for loop to go <= to the length and I added a condition to the if statement. This won't cause an index out of bounds because the if statement will short circuit before it tries to get the character at line.length().
    – haley
    Dec 24 '14 at 3:54




    Sorry about that! I changed the for loop to go <= to the length and I added a condition to the if statement. This won't cause an index out of bounds because the if statement will short circuit before it tries to get the character at line.length().
    – haley
    Dec 24 '14 at 3:54










    up vote
    1
    down vote













    If you aren't allowed to use ArrayList, or if you just think tail recursion is cool, you can do it this way:



    public static void main(String args) {

    System.out.println( getWordLengths("This is really easy") );
    }

    public static String getWordLengths( String s )
    {
    return "[" + getWordLengthsRecursively(s, 0, 0, 0) + "]";
    }

    public static String getWordLengthsRecursively( String s, int i, int start, int end )
    {
    // Last word
    if ( s.length() == i)
    {
    return "" + (end - start);
    }

    // Found a word
    if ( s.charAt(i) == ' ' )
    {
    return (end - start) + ", " + getWordLengthsRecursively(s, ++i, i, i);
    }

    // Word not found. Move to next character.
    else
    {
    return getWordLengthsRecursively(s, ++i, start, ++end);
    }
    }


    Output:



    [4, 2, 6, 4]


    I like it when I don't have to import anything. Don't you?






    share|improve this answer



























      up vote
      1
      down vote













      If you aren't allowed to use ArrayList, or if you just think tail recursion is cool, you can do it this way:



      public static void main(String args) {

      System.out.println( getWordLengths("This is really easy") );
      }

      public static String getWordLengths( String s )
      {
      return "[" + getWordLengthsRecursively(s, 0, 0, 0) + "]";
      }

      public static String getWordLengthsRecursively( String s, int i, int start, int end )
      {
      // Last word
      if ( s.length() == i)
      {
      return "" + (end - start);
      }

      // Found a word
      if ( s.charAt(i) == ' ' )
      {
      return (end - start) + ", " + getWordLengthsRecursively(s, ++i, i, i);
      }

      // Word not found. Move to next character.
      else
      {
      return getWordLengthsRecursively(s, ++i, start, ++end);
      }
      }


      Output:



      [4, 2, 6, 4]


      I like it when I don't have to import anything. Don't you?






      share|improve this answer

























        up vote
        1
        down vote










        up vote
        1
        down vote









        If you aren't allowed to use ArrayList, or if you just think tail recursion is cool, you can do it this way:



        public static void main(String args) {

        System.out.println( getWordLengths("This is really easy") );
        }

        public static String getWordLengths( String s )
        {
        return "[" + getWordLengthsRecursively(s, 0, 0, 0) + "]";
        }

        public static String getWordLengthsRecursively( String s, int i, int start, int end )
        {
        // Last word
        if ( s.length() == i)
        {
        return "" + (end - start);
        }

        // Found a word
        if ( s.charAt(i) == ' ' )
        {
        return (end - start) + ", " + getWordLengthsRecursively(s, ++i, i, i);
        }

        // Word not found. Move to next character.
        else
        {
        return getWordLengthsRecursively(s, ++i, start, ++end);
        }
        }


        Output:



        [4, 2, 6, 4]


        I like it when I don't have to import anything. Don't you?






        share|improve this answer














        If you aren't allowed to use ArrayList, or if you just think tail recursion is cool, you can do it this way:



        public static void main(String args) {

        System.out.println( getWordLengths("This is really easy") );
        }

        public static String getWordLengths( String s )
        {
        return "[" + getWordLengthsRecursively(s, 0, 0, 0) + "]";
        }

        public static String getWordLengthsRecursively( String s, int i, int start, int end )
        {
        // Last word
        if ( s.length() == i)
        {
        return "" + (end - start);
        }

        // Found a word
        if ( s.charAt(i) == ' ' )
        {
        return (end - start) + ", " + getWordLengthsRecursively(s, ++i, i, i);
        }

        // Word not found. Move to next character.
        else
        {
        return getWordLengthsRecursively(s, ++i, start, ++end);
        }
        }


        Output:



        [4, 2, 6, 4]


        I like it when I don't have to import anything. Don't you?







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 24 '14 at 9:13

























        answered Dec 24 '14 at 4:55









        candied_orange

        387219




        387219






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f74722%2fgetting-the-lengths-of-each-word-in-its-string-parameter%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

            List directoties down one level, excluding some named directories and files

            list processes belonging to a network namespace

            list systemd RuntimeDirectory mounts