Google Interview Question
Java DevelopersCountry: United States
public class Program
{
public static void Main()
{
var text = "Thank you for shopping at the XYZ Store.\nYour order has been processed successfully.\n";
Console.WriteLine(StringWrap(text,20));
}
public static string StringWrap(string text, int characters) {
StringBuilder sb = new StringBuilder();
string[] lines =text.Split('\n');
foreach(var line in lines) {
sb.Append(StringWrapLine(line, characters));
sb.Append("\n");
}
return sb.ToString();
}
public static string StringWrapLine(string text, int characters) {
string[] words =text.Split(' ');
StringBuilder sb = new StringBuilder();
int sum = 0;
foreach(var word in words) {
if(sum + word.Length <= characters) {
sb.Append(word + " ");
sum += word.Length + 1;
}
else {
sb.Length--;
sb.Append("\n");
sum = 0;
sb.Append(word + " ");
sum += word.Length + 1;
}
}
return sb.ToString();
}
}
public static void wrapText(String text, int characters){
int start = 0;
int end = 0;
int counter = 0;
for (int i = 0; i < text.length(); i++) {
if(i == text.length()-1){
System.out.println(text.substring(start, text.length()));
break;
}
if(counter< characters){
if(text.charAt(i)==' ')
end = i;
counter++;
}
else{
if(text.charAt(i)==' '){
System.out.println(text.substring(start, i));
start = i+1;
end =i+1;
}else{
System.out.println(text.substring(start, end));
start = end+1;
i = end;
end = start;
}
counter = 0;
}
}
- C# solution January 30, 2018