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