-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRemoveMultipleSpacesBetweenWords.java
65 lines (52 loc) · 1.38 KB
/
RemoveMultipleSpacesBetweenWords.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
package com.javamultiplex.string;
import java.util.Scanner;
public class RemoveMultipleSpacesBetweenWords {
public static void main(String[] args) {
Scanner input=null;
try
{
input=new Scanner(System.in);
System.out.println("Enter String : ");
String string=input.nextLine();
string=string.trim();
/*
* Regular expression that matches a string contains non-whitespace characters
* separated by at most one whitespace.
*/
String pattern="^([\\S]+\\s{0,1})+$";
if(string.matches(pattern))
{
System.out.println("String contains only single space between words.");
}
else
{
string=getStringAfterRemovingMultipleSpacesBetweenWords(string);
System.out.println("***String after removing multiple spaces.***\n"+string);
}
}
finally
{
if(input!=null)
{
input.close();
}
}
}
private static String getStringAfterRemovingMultipleSpacesBetweenWords(
String string) {
int length=string.length();
StringBuffer newString=new StringBuffer();
for(int i=0;i<length;i++)
{
if(!(Character.isWhitespace(string.charAt(i))))
{
newString.append(string.charAt(i));
if((i+1)<length && Character.isWhitespace(string.charAt(i+1)))
{
newString.append(string.charAt(i+1));
}
}
}
return newString.toString();
}
}