r/javahelp • u/Grand-Illustrator397 • Mar 20 '24
I hate strings
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner in = new Scanner(System.in);
String s = in.next();
String rest = s;
String result = ""; // empty string?
int i = 0;
while (rest.length() > 0)
{
String first = rest.substring(0,1); //extracts first character of 'rest' string
rest = rest.substring(1); // now it removes the first character?
if (rest.contains(first))
{
result = result + first; // what is being added if 'result' is empty
}
}
System.out.println(result);
}
}any video recomms for this type of use for loops and strings?? I tried using a table chart to understand a little better but it didnt work out for me, and i still dont understand how it works. Help would be appreaciated.
0
Upvotes
4
u/[deleted] Mar 21 '24 edited Mar 21 '24
What exactly is this code supposed to do? Pretty tough to read. Also .substring() is a doozy of a method of get used to since the first index is included, and the second is excluded. (I think. 15+ years of Java. I still read the documentation lol)
String is just a built-in, super convienant array of 'char'. They're actually pretty heavy on your computer. Try adding an array of integers to another, like ""+"" and you'll notice how nice this is for the concatenation of strings.
StringBuilder is the best way to simplify the concatenation. If you ever get around to decompile your compiled .class files, you'll see that the compiler actually converts all the ""+"" to the StringBuilder form. The compiler does a lot of optimizations like this for you.
^ important to note that inside a loop, it'll make a new StringBuilder each iteration. So declare it above the loop. Will make your loops MUCH faster.