public class StringClassTest { public static void main(String[] args) { //遍历字符串 String str = "Hello world"; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); System.out.print(ch+" "); } System.out.println(); //在字符串里查找子串并且返回其字串的第一个字母的小标,么找到返回-1 System.out.println(str.indexOf("llo")); System.out.println(str.indexOf("all")); //在字符串查找某个字符,找到返回下标,么找到返回-1 System.out.println(str.indexOf('l')); System.out.println(str.indexOf('a')); //给出要输出的字符串的起始小标和最终下标,输出字符串 String sub = str.substring(0,str.length()); System.out.println(sub); } }
输入一串字符判断其中数字,字母,其他的字符的个数程序如下:
public class WorkFour{ public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); int word = 0; int other = 0; int number = 0; for(int i = 0;i<str.length();i++){ char ch = str.charAt(i); if(Character.isLetter(ch)){ //判断字母的个数 word++; } else if(Character.isDigit(ch)){ number++; }else other++; } System.out.println(word+" "+number+" "+other); } }
String中的内存分析:
String str1 = new String("hello world");
String str2 = new String("hello world");
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
String str3 = "hello world";
System.out.println(str1 == str3);
String str4 = "hello world";
System.out.println(str3 == str4);