/
Java.java
72 lines (58 loc) · 2.19 KB
/
Java.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
72
/****************************************/
/* */
/* CodinGame.com Solutions by pathosDev */
/* */
/* Puzzle: Text formatting */
/* Difficulty: Easy */
/* Date solved: 13.11.2018 */
/* */
/****************************************/
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Solution
{
public static void main(String[] args)
{
//Read input.
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine().toLowerCase().trim();
//Remove excessive spaces.
text = text.replaceAll("\\s{2,}", " ");
//Remove spaces before and after punctuations.
Pattern regexPattern = Pattern.compile("\\s?\\p{P}\\s?");
Matcher regexMatcher = regexPattern.matcher(text);
while (regexMatcher.find())
{
String match = regexMatcher.group();
text = text.replaceAll(match.replace(".", "\\."), match.trim());
}
//Remove repeated punctuations.
regexPattern = Pattern.compile("\\p{P}+");
regexMatcher = regexPattern.matcher(text);
while (regexMatcher.find())
{
String match = regexMatcher.group();
text = text.replaceAll(match.replace(".", "\\."), match.trim().charAt(0) + "");
}
//First letter uppercase.
text = Arrays.stream(text.split("\\.", -1)).map(s -> stringToPascalCase(s)).collect(Collectors.joining("."));
//Add spaces after punctuations.
text = text.replaceAll("\\p{P}", "$0 ");
//Output formatted text.
System.out.println(text.trim());
}
//Converts any string to pascal case.
private static String stringToPascalCase(String s)
{
if (s == null || s.isEmpty())
{
return "";
}
char[] chars = s.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
return new String(chars);
}
}