File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+
2+ package reshape_string ;
3+
4+ import java .util .Scanner ;
5+
6+ /**
7+ *
8+ * @author JOSEPH
9+ *
10+ */
11+ public class Reshape_string {
12+ /*
13+ Statement
14+ The reshape(n, str) method should return the string str without spaces and layed out in lines of at most n characters.
15+ Examples:
16+ reshape(3, "abc de fghij") => returns "abc\ndef\nghi\nj"
17+ reshape(6, "1 23 456") => returns "123456"
18+ */
19+
20+ /**
21+ * @param args the command line arguments
22+ */
23+ public static void main (String [] args ) {
24+ Scanner input = new Scanner (System .in );
25+ String str ;
26+ int num ;
27+
28+ //insert a string and a number
29+ System .out .print ("Insert a string: " );
30+ str = input .nextLine ();
31+ System .out .print ("Insert the number of character: " );
32+ num = input .nextInt ();
33+
34+ //print the result of the reshape method
35+ System .out .println ("Result of reshape method: " +'\n' +reshape (num , str ));
36+ }
37+
38+ public static String reshape (int n , String str ) {
39+ //replace each space with empty string
40+ str = str .replace (" " , "" );
41+
42+ //insert a '\n' character each n characters
43+ String res = "" ;
44+ for (int i = 0 ; i < str .length (); i ++)
45+ {
46+ if (i %n == 0 && i != 0 )
47+ res = res +'\n' +str .charAt (i );
48+ else
49+ res += str .charAt (i );
50+ }
51+
52+ return res ;
53+ }
54+ }
You can’t perform that action at this time.
0 commit comments