zoukankan      html  css  js  c++  java
  • 关于JAVA的String类的一些方法

    一、得到字符串对象的有关信息

    1.通过调用length()方法得到String的长度.

    String str=”This is a String”;

    int len =str.length();

    2.StringBuffer类的capacity()方法与String类的 length()的方法类似,但是她测试是分配给StringBuffer的内存空间的大小,而不是当前被使用了的内存空间。

    3.如果想确定字符串中指定字符或子字符串在给定字符串的位置,可以用 indexOf()和lastIndexOf()方法。

    String str=”This is a String”;

    Int index1 =str.indexOf(“i”);   //index=2

    Int index2=str.indexOf(‘i’,index+1);   //index2=5

    Int index3=str.lastIndexOf(“I”);   //index3=15

    Int index4=str.indexOf(“String”);  //index4=10

    二、String 对象的比较和操作

    1.String 对象的比较

    String类的equals()方法用来确定两个字符串是否相等。

    String str=”This is a String”;

    Boolean result=str.equals(“This is another String “);

    //result=false

    2.String对象的访问

    A、方法charAt()用以得到指定位置的字符。

    String str=”This is a String”;

    char chr=str.charAt(3); //chr=”i”

    B、方法getChars()用以得到字符串的一部分字符串

    public void getChars(int srcBegin,int srcEnd,char[]dst,int dstBegin)

    String str=”This is a String”;

    Char chr =new char[10];

    Str.getChars(5,12,chr,0);  //chr=”is a St”

    C、subString()是提取字符串的另一种方法,它可以指定从何处开始提取字符串以及何处结束。

    3.操作字符串

    A、replace()方法可以将字符串中的一个字符替换为另一个字符。

    String str=”This is a String”;

    String str1=str.replace(‘T’,'t’); //str1=”this is a String”

    B、concat()方法可以把两个字符串合并为一个字符串。

    String str=”This is a String”;

    String str1=str.concat(“Test”); //str1=”This is a String Test”

    C、toUpperCase()和toLowerCase()方法分别实现字符串大小写的转换。

    String str=”THIS IS A STRING”;

    String str1=str.toLowerCase(); //str1=”this is a string”;

    D、trim()方法可以将字符串中开头和结尾处的空格去掉.

    String str=”This is a String   “;

    String str1=str.trim();   // str1=”This is a String”

    E、String 类提供静态方法valueOf(),它可以将任何类型的数据对象转换为一个字符串。如

    System.out.println(String,ValueOf(math,PI));

  • 相关阅读:
    Java relection half
    QT学习输入与输出
    FusionCharts(基于Flash的图表工具)使用心得
    测接口遇到的坑
    创建圆
    修改对象属性
    创建直线
    ObjectArx工程配置
    Excel转PDF文件,Excel转TIF文件
    创建多段线
  • 原文地址:https://www.cnblogs.com/420Rock/p/4905558.html
Copyright © 2011-2022 走看看