-3
public class solution {
    public static void main(String[] args) {
        String str = "The horse jumped over the sheep";
        String str1 = "";
        for(int i = 0; i!='\0'; i++); {
            if(str.charAt(i) != ' ')
                str1=str1+str.charAt(i);
        }
        System.out.println(str1);
    }
}

The program shows error at variable i. Is there any other means to print without white spaces without any in-built function?

StaticBeagle
  • 5,070
  • 2
  • 23
  • 34

2 Answers2

2

You have a ; after for loop here:

for (int i = 0; i != '\0'; i++)
    ;

Remove it and variable i would then be recognized.

Also your comparision of i with '\0' is wrong. I think you want to compare it till the end of the string str.

Which should be done like:

String str = "The horse jumped over the sheep";
String str1 = "";
for (int i = 0; i < str.length(); i++) {
    if (str.charAt(i) != ' ')
        str1 = str1 + str.charAt(i);
}
System.out.println(str1);

Outputs:

Thehorsejumpedoverthesheep

PS: I suggest you to read this post : String, StringBuffer, and StringBuilder as well.

Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29
0

(1) You need to remove the ; after the for loop to get rid of the error.

(2) I changed your for loop to a for-each loop as there was an error in your comparison (and it simplifies the code)

(3) I modified the code to include StringBuilder which will be more efficient when str becomes extremely long

String str = "a b c d";
StringBuilder str2 = new StringBuilder();
for (char c : str.toCharArray()) {
    if (c != ' ') {
        str2.append(c);
    }
}
System.out.println(str2);
orwinmc
  • 168
  • 1
  • 13