String类(判断和获取)
2015-07-19 15:51
453 查看
class StringDemo { public static void main(String[] args) { String s1="abc";//s1是一个类类型变量,所以“abc”是一个对象 //字符串最大的特点:一旦初始化就不可以被改变 s1="kk"; System.out.println(s1); } }
打印的是KK,不是变了吗?
这个一定要搞清,变的S1,“abc”对象没变还是“abc”;
class StringDemo { public static void main(String[] args) { String s1="abc"; String s2=new String("abc"); System.out.println(s1==s2); System.out.println(s1.equals(s2)); } }
s1和s2肯定不相等的,两个不同的对象
equals方法是比较地址值,但String类特殊,它复写Object类中的equals方法,该方法用于判断字符串是否相同
s1 和 s2的区别?
s1代表一个对象;
s2代表两个对象;
String类适用于字符创事物。
那么它就提供了多个方法对字符串进行操作。
常见的操作有哪些?
1:获取
a. 符串中包含的字符数,也就是字符串的长度。
int length() :获取长度
b. 根据位置获取某个字符;
char charAt (int index)
c. 根据字符获取该字符在字符串中的位置
int indexOf (int ch):返回的是ch在字符串中第一次出现的 位置
int indexOf (int ch , int fromIndex):从fromIndex指定位置开始,获取ch在字符串中出现的位置。
d. 根据字符串获取该字符串在字符串中的位置
int indexOf (String str):返回的是str在字符串中第一次出现的 位置
int indexOf (String str , int fromIndex):从fromIndex指定位置开始,获取str在字符串中出现的位置。
反向查找
int lastIndexof (int ch):从后往前找 注意大小写;
2:判断
a. 字符串中是否包含一个子串。
boolean contains(str)
特殊之处:indexOf(str):可以索引第一次出现的位置,如果放回-1,
表示不存在该字符串,所以,也可以用于对指定判断是否包含
if(str,indexOf("aa")!=-1)
而且该方法既可以判断,也可以获取出现位置
b. 字符中是否有内容
boolean isEmpty() :原理就是判断长度是否为0;
c. 字符串是否是以指定内容开头
boolean startsWith ( str );
d. 字符串是否是以指定内容结尾
boolean endsWith ( str );
e. 判断字符串内容是否相同,复写了Object类中的equals方法
boolean equals ( str );
f.
判断字符串内容是否相同,并忽略大小写。
boolean equalsIgnoreCase ( str );
3:转换
a. 将字符数组转成字符串。
构造函数:String(char [])
String(char [],offset,count):将字符数组中的一部分转成字符串。
b. 将字符串转成字符数组。
c. 将字节数组转成字符串。
d. 将字符串转成字节数组。
class StringDemo { public static void method_get() { String str="abcaeawf"; //获取长度 sop(str.length()); //根据位置获取某个字符 sop(str.charAt(4));//当访问到不存在的角标时会发生StringIndexOutOfBoundsException. //寻找字符的位置 sop(str.indexOf('m'));//如果没有返回-1 //从指定位置开始找 sop(str.indexOf('a',3)); //反向查找 sop(str.lastIndexOf('a')); } public static void main(String[] args) { method_get(); } public static void sop(Object obj) { System.out.println(obj); } }
class StringDemo { public static void method_is() { String str="ArrayDemo.java"; //判断文件是否以Array开头 sop(str.startsWith("Array")); //判断文件是否以.java结尾; sop(str.endsWith(".java")); //判断文件中是否有Demo sop(str.contains("Demo")); } public static void main(String[] args) { method_is(); } public static void sop(Object obj) { System.out.println(obj); } }
相关文章推荐
- (PowerDesigner&Sqlite)PD中设计完表后,将其导入数据库中
- URAL 1720 Summit Online Judge
- 剑指off-O(1)得到栈的最小元素
- 32位和64位系统区别及int字节数
- 创建精灵(基础总结)【7个属性】
- LINQ简介
- srm 541
- EM算法
- 灰度化
- SQL脚本积累之一-----UNION的使用示例
- [LeetCode]239.Sliding Window Maximum
- Linux strace命令(转)
- Poj2033
- 关于设计模式的思考
- PAT (Advanced Level) 1004. Counting Leaves (30) 层序遍历,两个queue辅助
- 如何查看/修改Linux时区和时间
- android 仿QQ界面
- C++ STL序列式容器优缺点记录
- Mysql数据库分布式事务XA详解
- C/C++位域知识小结