Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How to remove duplicate white spaces (including tabs, newlines, spaces, etc...) in a string using Java but not to remove duplicate white spaces in " " and ' ' quoted values within the input sptring ?

Input :

Select * 
  from emp 
  where name    =    'sanjiv    singh' 
  and    address   =   "ABC   sector  - 11";

Expected output :

Select * from emp where name = 'sanjiv    singh' and address = "ABC   sector  - 11";

I have tried it in the way: Iterated input string from start to end and ate duplicate white spaces only pointer is not between quoted value.
It is working fine in my case.

Is there any other way to achieve it ?

share|improve this question
2  
What have you tried so far? –  kocko 13 mins ago
    
The expected output doesn't have the white spaces removed. –  Maroun Maroun 12 mins ago
    
@kocko : Added my approach in question itself. –  Sanjiv 6 mins ago
    
Show your code, if it's working fine, what is your concrete issue? –  reto 4 mins ago

1 Answer 1

Try following code:

String test="Select * "+ 
                    "from emp "+ 
                    "where name =    'sanjiv    singh' "+ 
                    "and address = 'ABC   sector  - 11';";
        test=test.replaceAll("\\s+", " ");
        System.out.println(test);

Output :

Select * from emp where name = 'sanjiv singh' and address = 'ABC sector - 11';
share|improve this answer
    
This ignores the <<but not to remove duplicate white spaces in " " and ' ' quoted values within the input string>> part –  reto 6 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.