r/javahelp • • 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

21 comments sorted by

View all comments

4

u/[deleted] Mar 20 '24

When you need to manipulate Strings inside a loop consider using StringBuilder, it is more efficient as it mutates the inner character array and only creates the final String after you finished your algorithm.

3

u/Housy5 Nooblet Brewer Mar 21 '24

Since they still struggle with for loops and string manipulation. I doubt they should be caring about optimizing performance in a loop that probably wont go through enough iterations for it to really matter in the first place.

1

u/[deleted] Mar 21 '24

Fair enough. It is useful knowledge though.

1

u/amfa Mar 21 '24

afaik the compiler will use StringBuilder if possible on his own.

Don't if this will be the case here but in general it should not matter that much.

1

u/[deleted] Mar 21 '24

I... did not know this. I will verify, but thanks for the info