案例: 判断字符串中的字母和数字
describe
User will enter a random string,you need to judge there are how many letters of an alphabet and how many numbers;
related knowledges
class String
While coding in java,we usually to use String,luckly java has provided class String to creat and alter string.
(what you need to know is that the class String is in the package which named java.lang)
how to creat a string var?
EXAMPLE:
String a="abc";
this directly addignment will creat a const which located in const pool.
When you define the ‘a’=“abc” the jvm will search string “abc” in the const pool ,if there is ,the jvm will give the string’s location in the memory.
例如:
String a="abc";
String b="abc";
b="bca";
System.out.printf("a=%s\nb=%s",a,b);
输出结果
/Users/Admin/Library/Java/JavaVirtualMachines/openjdk-15.0.2/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=51435:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/Admin/IdeaProjects/study/out/production/study shuzu.Numandstr
a=abc
b=bca
进程已结束,退出代码为 0
String类的主要方法
返回指定索引处的值
charAt
public char charAt(int index);
example
// char a[]=new char[10];
String str=new String();
str="helloworld";
// a=str.toCharArray();//注意 charAt只能用于字符串,不能用于字符数组
System.out.println(str.charAt(0));
output
/Users/Admin/Library/Java/JavaVirtualMachines/openjdk-15.0.2/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=52150:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/Admin/IdeaProjects/study/out/production/study shuzu.Charat
h
进程已结束,退出代码为 0
compareTo
public class Test {
public static void main(String args[]) {
String str1 = "Strings";
String str2 = "Strings";
String str3 = "Strings123";
int result = str1.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);
result = str3.compareTo( str1 );
System.out.println(result);
}
}
output
0
-3
3
返回值
返回值是整型,它是先比较对应字符的大小(ASCII码顺序),如果第一个字符和参数的第一个字符不等,结束比较,返回他们之间的长度差值,如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方结束。