java学习--String类
来源:互联网 发布:网络模块 编辑:程序博客网 时间:2024/05/17 02:38
01)String(概述)
字符串(String)是由字符构成的一个序列。在Java语言中,字符串是一个对象。String类中有11个构造方法以及40多个处理字符串的方法
- public class StringDemo {
- public static void main(String[] args) {
- //字符串的特点:一旦被初始化就不可以改变。
- String s1 = "Hello world";//s是一个类类型变量,"Hello world"就是一个对象。
- String s = "Welcome to Java";//"Hello world"在内存中还存在,仅仅只是s这个引用指向了"Welcome to Java"。
- System.out.println(s);
- String s2 = new String("Hello world");
- /*
- * s1和s2有什么区别?
- * s1在内存中有一个对象。
- * s2在内存中有两个对象。
- */
- System.out.println(s1 == s2);//显示:false。
- System.out.println(s1.equals(s2));//显示:true。String类复写了Object类中equals方法。该方法用与判断字符串是否相等。
- }
- }
02)常见功能——获取和判断
- /*
- * String类用于描述字符串事物。
- * 那么它就提供了多个方法对字符串进行操作。
- *
- * 常见的操作有哪些?
- * "Hello world"
- * 1:获取。
- * 1.1:字符串中包含的字符数,也就是字串串的长度。int length():获取长度。
- * 1.2:根据位置获取位置上的某个字符。char charAt(int index):
- * 1.3:根据字符获取该字符在字符串的位置。int indexOf(int ch):返回的是ch在字符串中第一次出现的位置。indexOf(int ch, int fromIndex):返回在此字符串中第一次出现指定字符处的位置。
- * 2:判断。
- * 2.1:字符串中是否包含某一个字串。
- * 2.2:字符串中是否有内容。boolean isEmpty()
- * 2.3:字符串是否是以指定内容开头。boolean startsWith(str)
- * 2.4:字符串是否是以指定内容结尾。boolean endsWith(str)
- * 2.5:判断字符串内容是否相同。
- * 2.6:判断内容是否相同,并忽略大小写。
- */
- public class StringMethodDemo {
- public static void main(String[] args) {
- method_get();
- method_is();
- }
- public static void method_get(){
- String s = "Hello world";
- sop(s.length());//获取长度。
- sop(s.charAt(7));//获取下标为5的字符。注意:能发生字符串下标越界异常。
- sop(s.indexOf('o'));
- sop(s.indexOf('l', 3));//如果没有找到,返回-1。
- }
- public static void method_is(){
- String s = "StringMethodDemo.java";
- sop(s.startsWith("Str"));
- sop(s.endsWith(".java"));
- sop(s.contains("Method"));
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
03)转换
- /*
- * 3:转换
- * 3.1:将字符数组转成字符串。
- * 构造函数:String(Char[])
- * String(Char[], offset, count)
- * 静态方法:static String copyValueOf(char[])
- * static String copyValueOf(char[], offset, count)
- * 3.2:将字符串转成字符数组。
- * char[] toCharArray()
- * 3.3:将字节数组转成字符串。
- * 3.4:将字符串转成字节数组。
- * byte[] getBytes()
- * 3.5:将基本数据类型转换成字符串。
- * static String valueOf(int)
- * static String valueOf(double)
- *
- * 特殊:字符串和字节数组在转换过程中,是可以指定编码表的。
- */
- public class StringMethodDemo_2 {
- public static void main(String[] args) {
- method_trance();
- }
- public static void method_trance(){
- char[] arr = {'a', 'b', 'c', 'd', 'e'};
- String s1 = new String(arr);
- String s2 = new String(arr, 1, 3);
- sop("s1: " + s1);
- sop("s2: " + s2);
- String s3 = "Hello world";
- char[] chs3 = s3.toCharArray();
- for (int i = 0; i <chs3.length; i++){
- sop("chs3: " + chs3[i]);
- }
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
04)切割和替换
- /*
- * 4:替换
- * String replace(char oldChar, char newChar)
- * 5:切割
- * String[] split(String regex) 注意:如果字符串不匹配,将返回原来字符串。
- * 6:子串
- * String substring(int beginIndex) 注意:如果下标不存在,会发生字符串下标越界异常。
- * String substring(int beginIndex, int endIndex)
- */
- public class StringMethodDemo_3 {
- public static void main(String[] args) {
- method_replace();//替换
- method_split();//切割
- method_sup();//子串
- }
- public static void method_replace(){//替换
- String s = "Welcome to Java";
- String s1 = s.replace('o', 't');//将字符o替换成t
- String s2 = s.replace("to", "hehe");//将字符串to替换成hehe
- sop("s: " + s);//字符串一旦被初始化,s就不会被改变。
- sop("s1: " + s1);
- sop("s2: " + s2);
- }
- public static void method_split(){//切割
- String s = "hah, heh, heihei";
- String[] arr = s.split(", ");//如果不匹配就返回原值。
- for (int i = 0; i < arr.length; i++){
- sop(arr[i]);
- }
- }
- public static void method_sup(){//子串
- String s = "abcdefg";
- String s1 = s.substring(3);//从头到尾。//如果下标不存在,会发生字符串下标越界异常。
- String s2 = s.substring(3, 5);//包含头,不包含尾。
- sop("s: " + s);
- sop("s1: " + s1);
- sop("s2: " + s2);
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
05)比较和去空格
- /*
- * 7:转换,去空格,比较
- * 7.1:将字符串转换成大写或则小写。
- * String toLowerCase() //转换成小写
- * String toUpperCase() //转换成大写
- * 7.2:将字符串两端的空格去掉。
- * String trim()
- * 7.3:对两个字符串进行自然顺序的比较。
- * int compareTo(String anotherString)
- */
- public class StringMethodDemo_4 {
- public static void main(String[] args) {
- method_4();
- }
- public static void method_4(){//7:转换,去空格,比较
- String s = " Welcome to Java ";
- sop(s.toLowerCase());//转换成小写
- sop(s.toUpperCase());//转换成大写
- sop(s.trim());//去两端空格
- String s1 = "abc";
- String s2 = "aaa";
- sop(s1.compareTo(s2));
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
06)字符串练习(1)——去两端空格
- public class StringTest_1 {//去两端空格
- public static void sop(Object obj){
- System.out.println(obj);
- }
- public static void main(String[] args) {
- String s = " ab, ac, ad ";
- sop("(" + s + ")");//打印去空格前的字符串。
- sop("(" + myTrim(s) + ")");//去空格后。
- }
- //练习一,去除字符串两端空格。
- public static String myTrim(String str){
- int start = 0;
- int end = str.length() - 1;
- while(start <= end && str.charAt(start) == ' ')
- start++;
- while(start <= end && str.charAt(end) == ' ')
- end--;
- return str.substring(start, end + 1);
- }
- }
06)字符串练习(二)——将一个字符串进行反转
- /*
- * 练习二,将字符串进行反正。
- * 思路:
- * 1,将字符串变成数组。
- * 2,将数组进行反转。
- * 3,将数组变成字符串。
- */
- public class StringTest_2 {
- static Reverse_2 r = new Reverse_2();
- public static void sop(Object obj){
- System.out.println(obj);
- }
- public static void main(String[] args) {
- String s1 = " abc abc ";
- String s2 = " abc abc ";
- sop("(" + s1 + ")");
- System.out.println("------------------");
- sop("(" + reverseString(s1) + ")");//反转全部字符
- System.out.println("------------------");
- sop("(" + reverseString(s2) + ")");//反正指定位置字符
- }
- //练习二(1),将字符串进行反正。
- public static String reverseString(String s){//练习二(1)
- return r.reverseString(s, 0, s.length());
- }
- private static void reverse(char[] chs){//练习二(1)
- for (int start = 0, end = chs.length - 1; start < end; start++, end--){
- swap(chs, start, end);
- }
- }
- static void swap(char[] chs, int start, int end){//置换位置
- char temp = chs[start];
- chs[start] = chs[end];
- chs[end] = temp;
- }
- }
- class Reverse_2{
- //练习二(2),反转字符串中指定字符
- public static String reverseString(String s, int start, int end){//练习二(2)
- char[] chs = s.toCharArray();//1,将字符串变成数组。
- reverse(chs, start, end);//2,将数组中指定部分反转。
- return new String(chs);//3,将数组变成字符串。
- }
- private static void reverse(char[] chs, int a, int b){//练习二(2)
- for (int start = a, end = b - 1; start < end; start++, end--){
- StringTest_2.swap(chs, start, end);
- }
- }
- }
运行结果如下图所示:
07)字符串练习(三)——获取一个字符串在另一个字符串出现的次数
- public class StringTest_3 {
- public static void sop(Object obj){
- System.out.println(obj);
- }
- public static void main(String[] args) {
- String str = "hesafsheehesehesehesd";
- // sop("count = " + getSubCount(str, "he"));
- sop("count = " + getSubCount_2(str, "he"));
- }
- public static int getSubCount(String str, String key){//第一种方式
- int count = 0;
- int index = 0;
- while((index = str.indexOf(key)) != -1){
- sop("str = " + str);
- str = str.substring(index + key.length());//返回新字符串,从索引开始。
- count++;
- }
- return count;
- }
- public static int getSubCount_2(String str, String key){//第二种方式
- int count = 0;
- int index = 0;
- while((index = str.indexOf(key, index)) != -1){
- sop("index = " + index);
- index = index + key.length();//索引下标值加key长度。
- count++;
- }
- return count;
- }
- }
07)字符串练习(四)——获取两个字符串中最大相同子串。
- public class StringTest_4 {
- public static void sop(Object obj){
- System.out.println(obj);
- }
- public static void main(String[] args) {
- String s1 = "afhasdlkfhelfslohafasfadfa";
- String s2 = "affhelfsskd";
- sop(getMaxSubString(s1, s2));
- }
- public static String getMaxSubString(String s1, String s2){
- String max = "", min = "";
- max = (s1.length() > s2.length()) ? s1 : s2;//获取最长字符串,未知。
- min = (max == s1) ? s2 : s1;//如果最长字符串是s1,那么s2是最短字符串,否则s1是最短的。
- for (int i = 0; i < min.length(); i++){
- for (int j = i, k = min.length() - i; k != min.length() + 1; j++, k++){
- String temp = min.substring(j, k);//获取从下标j到(k-1)的字符串。
- if(s1.contains(temp))//如果最长字符串中包含字符串(temp)
- return temp;//那么返回temp。
- }
- }
- return "";
- }
- }
10)StringBuffer(常见功能——添加、删除和修改)
- /*
- * StringBuffer是字符串缓冲区。
- * 是一个容器。
- * 特点:
- * 1:长度是可变化的。
- * 2:可以直接操作多个数据类型。
- * 3:最终会通过toString()方法变成字符串。
- * 【C:create U:updete R:read D:delete】
- * 1:存储。
- * StringBuffer append():将指定数据作为参数添加到已有数据结尾处。
- * StringBuffer insert(index, 数据):将数据插入到指定index位置。
- * 2:删除。
- * StringBuffer delete(start, end):删除缓冲区中的数据,包含start,不包含end。
- * StringBuffer delete(index):删除指定位置的字符。
- * 3:获取。
- * char charAt(int index):
- * int indexOf(Strubg str):
- * int lastIndex(String str):
- * int length():
- * String subString(int start, int end):
- * 4:修改。
- * StringBuffer replace(int start, int end, String str):
- * void setCharAt(int index, char ch):
- * 5:反转
- * StringButffer reverse():
- */
- public class StringBufferDemo {
- public static void sop(String str){
- System.out.println(str);
- }
- public static void main(String[] args) {
- System.out.println("----------method_add----------");
- method_add();
- System.out.println("----------method_del----------");
- method_del();
- System.out.println("----------method_update----------");
- method_update();
- }
- public static void method_add(){//添加
- StringBuffer sb = new StringBuffer();
- sb.append("haha ").append(true).append(" " + 12345);//方法调用链。
- sb.insert(9, " hiahia ");//添加
- sop(sb.toString());
- }
- public static void method_del(){//删除
- StringBuffer sb = new StringBuffer("StringBufferDemo");
- sop(sb.toString());//删除前
- System.out.println("---------------");
- sb.delete(6, 8);//删除下标6到(8-1)的字符。
- sop(sb.toString());//删除后
- System.out.println("---------------");
- // sb.delete(0, 1);
- sb.deleteCharAt(0);//删除下标为0的字符。
- sop(sb.toString());
- sb.delete(0, sb.length());//清空缓冲区。
- sop(sb.toString());
- System.out.println("---------------");
- }
- public static void method_update(){
- StringBuffer sb = new StringBuffer("StringBufferDemo");
- sop(sb.replace(3, 6, "java").toString());//返回StrjavaBufferDemo。
- sb.setCharAt(3, 'J');
- sop(sb.toString());//返回StrJavaBufferDemo。
- }
- }
11)StringBuilder
一个可变的字符序列。该类被设计用作
StringBuffer
的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比StringBuffer
要快。- /*
- * JDK1.5之后出现StringBuilder。
- * StringBuffer:线程是同步的。
- * StringBuilder:线程不同步。
- * 将 StringBuilder 的实例用于多个线程是不安全的。如果需要这样的同步,则建议使用 StringBuffer。
- * 升级三个因数:
- * 1:提高效率
- * 2:简化书写
- * 3:提高安全性
- */
12)基本数据类型对象包装类
- /*
- * 基本数据类型对象包装类。
- * byte Byte
- * short Short
- * int Integer
- * long Long
- * boolean Boolean
- * float Float
- * double Double
- * char Character
- *
- * 最常见作用:用于基本数据类型和字符串类型之间做转换。
- * 基本数据类型转字符串类型:(基本数据类型 + "")(基本数据类型.toString(基本数据类型值))
- * 字符串类型转基本数据类型:数据类型 变量 = 基本数据类型包装类.parse数据类型(""):
- *
- * 十进制转成其它进制:toBinaryString()、toHexString()、toOctalString()
- * 其它进制转成十进制:parseInt(String s, int index)
- */
- public class IntegerDemo {
- public static void sop(String str){
- System.out.println(str);
- }
- public static void main(String[] args) {
- //整数类型的最大值。
- sop("Int max = " + Integer.MAX_VALUE);
- System.out.println("---------------------");
- //将一个整数转成字符串。
- String num1 = Integer.toString(20);
- System.out.println("num1 = " + num1);
- sop("num1 = " + (num1 + 1));
- System.out.println("---------------------");
- //将一个字符串转成一个整数。
- int num2 = Integer.parseInt("20");//必须输入数字格式的字符串。
- sop("num2 = " + (num2 + 2));
- System.out.println("---------------------");
- //
- int a = Integer.parseInt("10101010", 2);
- int b = Integer.parseInt("3c", 16);
- sop("a = " + a);
- sop("b = " + b);
- System.out.println("---------------------");
- }
- }
14)新特性
- public class IntegerDemo_2 {
- public static void sop(String str){
- System.out.println(str);
- System.out.println("------------------");
- }
- public static void main(String[] args) {
- method_1();
- method_2();
- }
- public static void method_1(){
- Integer a = new Integer("123");
- Integer b = new Integer(123);
- sop("a==b? " + (a == b));
- sop("a.equals(b)? " + (a.equals(b)));
- }
- public static void method_2(){
- Integer c = 110;//自动装箱。 110等于Integer(10)。
- sop("c = " + c);
- c = c + 1;//先自动拆箱c(c.intValue()),与1向加后,在将值自动装箱。
- sop("c = " + c);
- Integer d = 128;//byte数据类型的零界点。
- Integer e = 128;
- sop("d==e? " + (d == e));
- Integer f = 120;
- Integer g = 120;
- sop("f==g? " + (f == g));//f和g指向同一个对象。
- }
- }
0 0
- 学习java String类
- JAVA String类学习
- Java学习-String类
- java学习--String类
- java-学习-string类
- Java学习 String 类
- java学习笔记---String类
- java学习笔记---String类
- JAVA学习【知】String类
- java学习之String类
- Java学习之String类
- java学习之String类
- Java学习之string类
- Java学习笔记:String类
- Java 学习之 String类
- JAVA进阶学习-java String类
- java学习笔记五--String类与String例子
- JAVA学习十八:String类、StrinBuffer类
- javascript之cookie对象
- hadoop命令介绍
- 厂家直销纯棉浴巾玫瑰花浴巾毛巾批发
- JAVA:Random的种子含义
- EXCEL二级联动设置
- java学习--String类
- 性能测试知多少--系统计数器与硬件分析
- 马云:10年后癌症光临每个家庭
- Lowest Bit
- android中listView下拉刷新
- 剑指offer系列源码-栈的压入、弹出序列
- 【转载】关于aspectJ无法被eclipse加入类路径的分析和解决
- Android 震 动
- 【删除菜单项或者菜单项中的子菜单】