I want to write a program which cut letters from the end of a string until the last letter is the same as first. For example:
"kokota" --> "kok"
"alinak" --> "alina"
"kocur" ---> k etc.
I tried doing it like this:
And program prints s string so its content isn't modified.import java.util.Scanner; public class zad681 { public static String funkyFunction (String s) { for(int i = s.length() - 1; i > 0; i--){ if(s.charAt(i) == s.charAt(0)){ s.substring(0, i); } } return s; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Wprowadź zdanie:"); String content = scan.nextLine(); String[] words = content.split("\\s+"); for(int i = 0; i < words.length; i++){ System.out.println(zad681.funkyFunction(words[i])); } System.out.println(zad681.funkyFunction("ala ma kotka")); } }
I think using substring and charAt is good idea. Thank you from your answers.