-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBreakStringIntoTexts.java
71 lines (60 loc) · 1.28 KB
/
BreakStringIntoTexts.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.util.*;
public class BreakStringIntoTexts
{
public static void main(String[] args)
{
String s = "I beautiful you are singing excessivel peculiar";
int k = 18;
List<String> myList = breakStringIntoTexts(s, k);
if(myList == null)
{
System.out.println("Unable to break text");
}
else
{
for (String text : myList)
{
System.out.println(text);
}
}
}
public static List<String> breakStringIntoTexts(String s, int k)
{
List<String> list = new ArrayList<>();
String[] sArray = s.split(" ");
/* if there is any word whose length is greater than k then
we are unable to break the string up into k length text
so we break out of the function */
for(int i = 0; i < sArray.length; i++)
{
if(sArray[i].length() > k)
{
list = null;
return list;
}
}
StringBuilder builder = new StringBuilder();
builder.append(sArray[0]);
int i = 1;
String text;
while(i < sArray.length)
{
if(builder.length() + sArray[i].length() + 1 <= k)
{
builder.append(" ");
builder.append(sArray[i]);
}
else
{
text = builder.toString();
list.add(text);
builder = new StringBuilder();
builder.append(sArray[i]);
}
i++;
}
text = builder.toString();
list.add(text);
return list;
}
}