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 ie str.replaceAll(), Can anyone help me with the program.I want same output as I got using library function
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);
}
}
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
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?
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);
}
}
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]);
}
}}
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.