比方:输入name输出n,输入teeter输出r,输入namename输出null
细致完成代码以下:
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; } } } }
在线视频教程引荐:java视频
在这个完成代码中我们运用了String类的三个要领成员:
String.length()
:猎取字符串的长度
String.charAt(int index)
:猎取索引index的字符
String.lastIndexOf(char c)
:猎取字符c末了一次涌现在字符串中的索引
String.indexOf(char c)
:猎取字符c第一次涌现在字符串中的索引
实在我们也能够不运用字符串的这些要领就能够完成了,下面是个人运用for轮回来完成的代码:
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; } } } }
这类要领能够完成,不过这类要领的时候复杂度迥殊的大,体系开支也迥殊大,因而我们最好不要运用轮回嵌套,除非必不得已,不然对体系开支是很大的。
相干文章教程引荐:java疾速入门
以上就是java怎样完成猎取字符串中第一个涌现不反复的字符的细致内容,更多请关注ki4网别的相干文章!