• Java String简单知识点总结


    1.字符串的比较

     1 public void run(){
     2         //str1在池中
     3         String str1 = new String("String");
     4         //str2,str3 存在于堆中
     5         String str2 = "String";
     6         String str3 = "strin"+"g";
     7         
     8         System.out.println(str1 == str2);//false
     9         
    10         System.out.println(str1.equals(str2));//true
    11         
    12         System.out.println(str1.equalsIgnoreCase(str3));//true
    13         
    14         System.out.println(str1.toLowerCase().equals(str3));//true
    15         
    16     }
    •==”和equals()有什么区别呢?

    equals():检查组成字符串内容的字符是否完全一致

    ==:判断两个字符串在内存中的首地址,即判断是否是同一个字符串对象

    2.字符串的连接

     1 public void run(){
     2         //str1在池中
     3         String str1 = new String("String");
     4         //str2存在于堆中
     5         String str2 = "String";
     6         //方法1:
     7         String str3 = str2+"fff";
     8         //方法2:
     9         String str4 = str2.concat("ffff");
    10         
    11     }

    3.字符串的提取

      方   法

    说   明

    public int indexOf(int ch)

    搜索第一个出现的字符ch(或字符串value)

    public int indexOf(String value)

    public int lastIndexOf(int ch)

    搜索最后一个出现的字符ch(或字符串value)

    public int lastIndexOf(String value)

                                         返回出现第一个匹配的位置,如果没有找到字符或字符串,则返回-1;

    方  法

                说  明

    public String substring(int index)

    提取从位置索引开始的字符串部分

    public String substring(int beginindex, int endindex)

    提取beginindex和endindex之间的字符串部分

    public String trim()

    返回一个前后不含任何空格的调用字符串的副本

                                       beginindex: 字符串的位置从0开始算,endindex: 字符串的位置从1开始算;

    4.字符串的拆分

    •String类提供了split()方法,将一个字符串分割为子字符串,结果作为字符串数组返回
     1 public void run(){
     2 
     3         String words="长亭外 古道边 芳草碧连天 晚风扶 柳笛声残 夕阳山外山";
     4         String[] printword=new String[100];        
     5            System.out.println("***原歌词格式***
    "+words);
     6         System.out.println("
    ***拆分后歌词格式***");
     7         printword=words.split(" "); 
     8         for(int i=0;i<printword.length;i++){
     9             System.out.println( printword[i] );
    10         }
    11     
    12 
    13     }

    5.字符串的创建

    •在Java执行时会维护一个String池(Pool),当直接在程序中使用“”来包括一个字符串时,该字符串就会在String池中。
    •对于一些可以共享的字符串对象,会先在String池中查找是否存在相同的String内容(字符相同),如果有就直接返回,而不是直接创造一个新的String对象,以减少内存的耗用。

    在intern()方法被调用时,如果池(Pool)中已经包括了相同的String对象(相同与否由equals()方法决定),那么会从池中返回该字符串,否则原String对象会被加入池中,并返回这个String对象的引用。

     
  • 相关阅读:
    我为何看到你的提问不想回答?关于如何提问的一些看法
    零基础一步一步pytorch实现Logistic regression逻辑回归编程教程
    numpy与pytorch实现梯度下降,实现一个简单的两层神经网络
    [ubuntu]Gedit修改文件后提示无法创建备份文件同时不能保存修改过后的文件
    【测绘】高速公路中线放样
    【GDAL】图像处理三:图像平滑(一)
    【GDAL】图像处理二:初级图像读取,操作,存储。
    【GDAL】图像处理一:GDAL1.9.2在vs2010旗舰版中的配置
    【openCV】openCV2.4.8在vs2010旗舰版中的配置
    【c++】大数相加
  • 原文地址:https://www.cnblogs.com/ezreal2016/p/5768850.html
Copyright © 2020-2023  润新知