-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReverseStringWithoutReversingWords.java
128 lines (98 loc) · 2.53 KB
/
ReverseStringWithoutReversingWords.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package com.javamultiplex.string;
import java.util.Scanner;
public class ReverseStringWithoutReversingWords {
public static void main(String[] args) {
Scanner input=null;
try
{
input=new Scanner(System.in);
System.out.println("Enter String: ");
String string=input.nextLine();
if(isOnlyOneWordString(string))
{
System.out.println("This is single word string, Please enter string with atleast 2 words.");
}
else
{
if(isMultipleSpacesExistBetweenWords(string))
{
string=getStringAfterRemovingMultipleSpacesBetweenWords(string);
}
string=getReversedString(string);
string=getStringAfterReversingIndivisualWords(string);
System.out.println("Reveresed String without reversing indivisual words is :\n"+string);
}
}
finally
{
if(input!=null)
{
input.close();
}
}
}
private static String getStringAfterReversingIndivisualWords(String string) {
String space=" ";
String[] words=string.split(space);
String word=null;
StringBuffer result=new StringBuffer();
int length=words.length;
for(int i=0;i<length;i++)
{
word=words[i];
word=getReversedString(word);
result.append(word);
if(i!=(length-1))
{
result.append(space);
}
}
return result.toString();
}
private static String getReversedString(String word) {
String string="";
int length=word.length();
for(int i=length-1;i>=0;i--)
{
string+=word.charAt(i);
}
return string;
}
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();
}
private static boolean isMultipleSpacesExistBetweenWords(String string) {
String newString=string.trim();
String pattern="([\\S]+\\s{0,1})+";
boolean result=true;
if(newString.matches(pattern))
{
result=false;
}
return result;
}
private static boolean isOnlyOneWordString(String string) {
String newString=string.trim();
boolean result=false;
String pattern="^[\\S]+$";
if(newString.matches(pattern))
{
result=true;
}
return result;
}
}