5

I have a funtion in my program that should determine if the last char of a string is a / and if not, add a / at the end, however, it always adds a /, even if the last char is a / Here is the code:

public static String setLastCharSlash(String check) {
    if(check.substring(check.length() - 1) != "/") {
        check = check + "/";
    }
    return check;
}
ichttt
  • 95
  • 1
  • 1
  • 5
  • 1
    `return check.endsWith("/") ? check : (check + "/");` is better: it avoids creating a new string unnecessarily. – Andy Turner Oct 17 '16 at 17:54
  • This is not a duplicate of "How do I compare strings in Java?". It's an unrelated question how to chat the value of the last character. – Steve Kuo Oct 17 '16 at 18:00
  • The problem is that != compares the two objects and checks whether they are the same, but they are just similar. To check similarity instead, use the .equals() function, like this: check.substring(check.length() - 1).equals("/") – Lajos Arpad Oct 18 '16 at 17:27
  • @SteveKuo the problem here is they compare strings incorrectly so it's a duplicate. – ivan_pozdeev Oct 18 '16 at 22:03

1 Answers1

13

There's a specific method for this use case:

boolean isSlashLast = "your/string/".endsWith("/");
rorschach
  • 2,871
  • 1
  • 17
  • 20