For example: input name and output n, input teeter and output r, input namename and output null
The specific implementation code is as follows:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.next(); for(int i =0 ; i < str.length() ; i++) { if(str.lastIndexOf(str.char(i)) == i && str.indexOf(str.char(i)) == i) { System.out.println(str.char(i)); break; } } } }
Online Video tutorial recommendation: java video
In this implementation code we use three method members of the String class:
String.length( )
: Get the length of the string
String.charAt(int index)
: Get the character of the index index
String.lastIndexOf(char c )
: Get the index of the last time character c appears in the string
String.indexOf(char c)
: Get the index of the first time character c appears in the string
In fact, we can also implement these methods without using strings. The following is the code that I personally use for loop to implement:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.next(); char[] cb = new char[str.length()]; //将字符串中的字符一次存入cb[] for(int i =0 ;i <str.length() ; i++) { cb[i] = str.charAt(i); } for(int i = 0 ; i < str.length() ; i++) { for(int j = 0 ; j < str.length() ; j++) { if(cb[i] == cb[j] && cb[i] != '0') { char c = cb[i]; for(int z = 0 ; z < str.length() ; z++) { if(cb[z] == c) cb[z] = '0'; } } } } for(int i = 0 ; i <str.length() ; i++) { if(cb[i] != '0') { System.out.println(cb[i]); break; } } } }
This method can be implemented, but this method The time complexity is extremely large, and the system overhead is also extremely large. Therefore, it is best not to use loop nesting unless it is absolutely necessary, otherwise the system overhead will be very large.
Recommended related articles and tutorials: java quick start
The above is the detailed content of How to get the first non-repeating character in a string in java. For more information, please follow other related articles on the PHP Chinese website!