- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStringTrimExample.java
More file actions
Latest commit
39 lines (30 loc) · 980 Bytes
/
Copy pathStringTrimExample.java
File metadata and controls
39 lines (30 loc) · 980 Bytes
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
importjava.util.Scanner;
/**
* 32. How to remove space in string both end and middle extra space in java
* Program
*
*/
publicclassStringTrimExample {
publicstaticvoidmain(String[] args) {
try (Scannerscanner = newScanner(System.in)) {
System.out.println("=== String Trim Program ===");
while (true) {
System.out.print("\nEnter a sentence (type 'exit' to quit): ");
Stringinput = scanner.nextLine();
// Exit condition
if (input.equalsIgnoreCase("exit")) {
System.out.println("Program terminated.");
break;
}
// Remove leading and trailing spaces
Stringtrimmed = input.trim();
System.out.println("Sentence with trim: " + trimmed);
// Normalize spaces between words
Stringnormalized = trimmed.replaceAll("\\s+", " ");
System.out.println("Sentence with single spaces: " + normalized);
}
} catch (Exceptione) {
System.out.println("Unexpected error occurred: " + e.getMessage());
}
}
}