'how to remove spaces in between string in java,without using library function?
I am getting the solution is as follows
class StringCheck
{
public static void main (String[] args)
{
String str="Hello world I am here";
String r;
System.out.println(str);
r = str.replaceAll(" ","");
System.out.println(r);
}
}
OUTPUT: HelloworldIamhere
but I don't want to use a library function i.e str.replaceAll(), Can anyone help me with the program.I want same output as I got using library function
Solution 1:[1]
What I understood from your question is you don't want to use str.replaceAll() function. So possible alternative is following. Please refer more details Removing whitespace from strings in Java
import java.util.*;
public class StringCheck {
public static void main(String[] args) {
String str = "Hello world I am here";
String r = "";
Scanner sc = new Scanner(str);
while(sc.hasNext()) {
r += sc.next();
}
System.out.println(r);
}
}
Solution 2:[2]
Iterate each char in str.
If it is not equal ' ', append it to your result string r.
But why would you want to do it without using library functions?
Solution 3:[3]
Well as you do not want to keep the value just loop and print
String str="Hello world I am here";
for (char c : str.toCharArray()) {
if (c != ' ')
System.out.print(c);
}
output
HelloworldIamhere
Of course if you wanted to keep this new String then use a StringBuilder and append the char instead of/and print it
Solution 4:[4]
public class Removespaces {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
char[] ch = s.toCharArray();
String s1 = "";
for(int i=0;i<ch.length;i++){
if(s.charAt(i)==' ')
{
continue;
}else{
s1 = s1 + s.charAt(i);
}
}
System.out.println(s1);
}
}
Solution 5:[5]
Hey I have solution for that question you can have this way. I didn’t use in-build function
public class RemoveSpace {
public static void main(String[] args) {
String str="Abd is a good guy";
char[] a=str.toCharArray();
System.out.println(a);
int size=a.length;
for(int i=0; i<size;i++)
{
if(a[i]==32)
{
for(int j=i;j<size-1;j++)
{
a[j]=a[j+1];
}
size--;
}
}
for(int i=0; i<size; i++)
{
System.out.print(a[i]);
}
}}
Solution 6:[6]
String s = "Hello world I am here";
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (c != ' ') {
sb.append(c);
}
}
System.out.println(sb.toString());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sandun Madola |
| Solution 2 | Community |
| Solution 3 | |
| Solution 4 | Roberto Caboni |
| Solution 5 | |
| Solution 6 | xlm |
