我的java学习日记(八)

案例: 判断字符串中的字母和数字

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码顺序),如果第一个字符和参数的第一个字符不等,结束比较,返回他们之间的长度差值,如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方结束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值