Modifying strings in Java practice -
this question has answer here:
- indexof in string array 6 answers
public static void displaywords(string line) { // while line has length greater 0 // find index of space. // if there one, // print substring 0 space // change line substring space end // else // print line , set equal empty string } line = "i love you"; system.out.printf("\n\n\"%s\" contains words:\n", line ); displaywords(line);
hi, i'm having trouble above code, it;s practice problem "change line substring space end" confuses me. know how find index of space , printing string beginning index.
expected output:
i love
slaks recommending in comment use substring()
method. checking api documentation string
:
public string substring(int beginindex, int endindex)
returns new string substring of string. substring begins @ specified
beginindex
, extends character @ indexendindex - 1
. length of substringendindex-beginindex
.examples:
"hamburger".substring(4, 8)
returns"urge"
"smiles".substring(1, 5)
returns"mile"
so, consider this:
public static void displaywords(string line) { while(line.length() > 0) { // first part (the obvious one) /* should here tracks index of first space character in line. suggest check `charat()` method, , use for() loop. let's find space @ index */ system.out.println(line.substring(0,i)); // prints substring of line // goes beginning // (index 0) position right // before space /* finally, here should assign new value line, value must start after found space , end @ end of line. hint: use substring() again, , remember line.lengh() give position of last character of line plus one. */ } }
you've had enough time... , i'm feeling generous tonight. here solution:
public static void displaywords(string line) { int i; // you'll need while(line.length() > 0) { // first part (the obvious one) /* here, check each character , if find space, break loop */ for(i = 0; < line.length(); i++) { if(line.charat(i) == ' ') // if character @ index space ... break; // ... break loop } system.out.println(line.substring(0,i)); // prints substring of line // goes beginning // (index 0) position right // before space /* here, new value of line substring position of space plus 1 end of line. if greater length of line you're done. */ if(i < line.length()) line = line.substring(i + 1, line.length()); else line = ""; } }
after reading question again, realised should recursive solution... here recursive approach:
public static void displaywords(string line) { int i; for(i = 0; < line.lengh(); i++) { if(line.charat(i) = ' ') break; } system.out.println(line.substring(0, i); if(i < line.lengh()) line = line.substring(i + 1, line.lengh(); else line = ""; if(line.lengh() > 0) displaywords(line); }
Comments
Post a Comment