android——字符串string(转)

原文地址:http://www.open-open.com/lib/view/open1387942832078.html

String : 字符串类型

一、构造函数
     String(byte[ ] bytes):通过byte数组构造字符串对象。
     String(char[ ] value):通过char数组构造字符串对象。
     String(Sting original):构造一个original的副本。即:拷贝一个original。
     String(StringBuffer buffer):通过StringBuffer数组构造字符串对象。  
例如:
      byte[] b = {‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘};
      char[] c = {‘0‘,‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘};
      String sb = new String(b);                 //abcdefghij
      String sb_sub = new String(b,3,2);     //de
      String sc = new String(c);                  //0123456789
      String sc_sub = new String(c,3,2);    //34
      String sb_copy = new String(sb);       //abcdefghij  
      System.out.println("sb:"+sb);
      System.out.println("sb_sub:"+sb_sub);
      System.out.println("sc:"+sc);
      System.out.println("sc_sub:"+sc_sub);
      System.out.println("sb_copy:"+sb_copy);
      输出结果:sb:abcdefghij
                      sb_sub:de
                       sc:0123456789
                        sc_sub:34
                        sb_copy:abcdefghij

二、方法:

说明:①、所有方法均为public。
           ②、书写格式: [修饰符] <返回类型><方法名([参数列表])>

例如:static int parseInt(String s)
      表示此方法(parseInt)为类方法(static),返回类型为(int),方法所需要为String类型。

1. char charAt(int index) :取字符串中的某一个字符,其中的参数index指的是字符串中序数。字符串的序数从0开始到length()-1 。
    例如:String s = new String("abcdefghijklmnopqrstuvwxyz");
          System.out.println("s.charAt(5): " + s.charAt(5) );
          结果为: s.charAt(5): f
2. int compareTo(String anotherString) :当前String对象与anotherString比较。相等关系返回0;不相等时,从两个字符串第0个字符开始比较,返回第一个不相等的字符差,另一种情况,较长字符串的前面部分恰巧是较短的字符串,返回它们的长度差。
3. int compareTo(Object o) :如果o是String对象,和2的功能一样;否则抛出ClassCastException异常。
    例如:String s1 = new String("abcdefghijklmn");
            String s2 = new String("abcdefghij");
           String s3 = new String("abcdefghijalmn");
           System.out.println("s1.compareTo(s2): " + s1.compareTo(s2) ); //返回长度差
           System.out.println("s1.compareTo(s3): " + s1.compareTo(s3) ); //返回‘k‘-‘a‘的差
           结果为:s1.compareTo(s2): 4
                       s1.compareTo(s3): 10
4. String concat(String str) :将该String对象与str连接在一起。
5. boolean contentEquals(StringBuffer sb) :将该String对象与StringBuffer对象sb进行比较。
6. static String copyValueOf(char[] data) :
7. static String copyValueOf(char[] data, int offset, int count) :这两个方法将char数组转换成String,与其中一个构造函数类似。
8. boolean endsWith(String suffix) :该String对象是否以suffix结尾。
    例如:String s1 = new String("abcdefghij");
           String s2 = new String("ghij");
           System.out.println("s1.endsWith(s2): " + s1.endsWith(s2) );
           结果为:s1.endsWith(s2): true
9. boolean equals(Object anObject) :当anObject不为空并且与当前String对象一样,返回true;否则,返回false。
10. byte[] getBytes() :将该String对象转换成byte数组。
11. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) :该方法将字符串拷贝到字符数组中。其中,srcBegin为拷贝的起始位置、srcEnd为拷贝的结束位置、字符串数值dst为目标字符数组、dstBegin为目标字符数组的拷贝起始位置。
     例如:char[] s1 = {‘I‘,‘ ‘,‘l‘,‘o‘,‘v‘,‘e‘,‘ ‘,‘h‘,‘e‘,‘r‘,‘!‘};//s1=I love her!
           String s2 = new String("you!"); s2.getChars(0,3,s1,7); //s1=I love you!
           System.out.println( s1 );
           结果为:I love you!
12. int hashCode() :返回当前字符的哈希表码。
13. int indexOf(int ch) :只找第一个匹配字符位置。
14. int indexOf(int ch, int fromIndex) :从fromIndex开始找第一个匹配字符位置。
15. int indexOf(String str) :只找第一个匹配字符串位置。
16. int indexOf(String str, int fromIndex) :从fromIndex开始找第一个匹配字符串位置。
      例如:String s = new String("write once, run anywhere!");
              String ss = new String("run");
              System.out.println("s.indexOf(‘r‘): " + s.indexOf(‘r‘) );
              System.out.println("s.indexOf(‘r‘,2): " + s.indexOf(‘r‘,2) );
              System.out.println("s.indexOf(ss): " + s.indexOf(ss) );
              结果为:s.indexOf(‘r‘): 1
                      s.indexOf(‘r‘,2): 12
                      s.indexOf(ss): 12
17. int lastIndexOf(int ch)
18. int lastIndexOf(int ch, int fromIndex)
19. int lastIndexOf(String str)
20. int lastIndexOf(String str, int fromIndex) 以上四个方法与13、14、15、16类似,不同的是:找最后一个匹配的内容。
public class CompareToDemo {
      public static void main (String[] args) {
           String s1 = new String("acbdebfg");
      
           System.out.println(s1.lastIndexOf((int)‘b‘,7));
     }
}
运行结果:5
       (其中fromIndex的参数为 7,是从字符串acbdebfg的最后一个字符g开始往前数的位数。既是从字符c开始匹配,寻找最后一个匹配b的位置。所以结果为 5)

21. int length() :返回当前字符串长度。
22. String replace(char oldChar, char newChar) :将字符号串中第一个oldChar替换成newChar。
23. boolean startsWith(String prefix) :该String对象是否以prefix开始。
24. boolean startsWith(String prefix, int toffset) :该String对象从toffset位置算起,是否以prefix开始。
     例如:String s = new String("write once, run anywhere!");
             String ss = new String("write");
             String sss = new String("once");
             System.out.println("s.startsWith(ss): " + s.startsWith(ss) );
             System.out.println("s.startsWith(sss,6): " + s.startsWith(sss,6) );
             结果为:s.startsWith(ss): true
                     s.startsWith(sss,6): true
25. String substring(int beginIndex) :取从beginIndex位置开始到结束的子字符串。
26.String substring(int beginIndex, int endIndex) :取从beginIndex位置开始到endIndex位置的子字符串。
27. char[ ] toCharArray() :将该String对象转换成char数组。
28. String toLowerCase() :将字符串转换成小写。
29. String toUpperCase() :将字符串转换成大写。
     例如:String s = new String("java.lang.Class String");
             System.out.println("s.toUpperCase(): " + s.toUpperCase() );
             System.out.println("s.toLowerCase(): " + s.toLowerCase() );
             结果为:s.toUpperCase(): JAVA.LANG.CLASS STRING
                  s.toLowerCase(): java.lang.class string
30. static String valueOf(boolean b)
31. static String valueOf(char c)
32. static String valueOf(char[] data)
33. static String valueOf(char[] data, int offset, int count)
34. static String valueOf(double d)
35. static String valueOf(float f)
36. static String valueOf(int i)
37. static String valueOf(long l)
38. static String valueOf(Object obj)
     以上方法用于将各种不同类型转换成Java字符型。这些都是类方法。

Java中String类的常用方法:

public char charAt(int index)
返回字符串中第index个字符;
public int length()
返回字符串的长度;
public int indexOf(String str)
返回字符串中第一次出现str的位置;
public int indexOf(String str,int fromIndex)
返回字符串从fromIndex开始第一次出现str的位置;
public boolean equalsIgnoreCase(String another)
比较字符串与another是否一样(忽略大小写);
public String replace(char oldchar,char newChar)
在字符串中用newChar字符替换oldChar字符
public boolean startsWith(String prefix)
判断字符串是否以prefix字符串开头;
public boolean endsWith(String suffix)
判断一个字符串是否以suffix字符串结尾;
public String toUpperCase()
返回一个字符串为该字符串的大写形式;
public String toLowerCase()
返回一个字符串为该字符串的小写形式
public String substring(int beginIndex)
返回该字符串从beginIndex开始到结尾的子字符串;
public String substring(int beginIndex,int endIndex)
返回该字符串从beginIndex开始到endsIndex结尾的子字符串
public String trim()
返回该字符串去掉开头和结尾空格后的字符串
public String[] split(String regex)
将一个字符串按照指定的分隔符分隔,返回分隔后的字符串数组
实例:  
public class SplitDemo{
     public static void main (String[] args) {

String date = "2008/09/10";
            String[ ] dateAfterSplit= new String[3];
            dateAfterSplit=date.split("/");         //以“/”作为分隔符来分割date字符串,并把结果放入3个字符串中。

for(int i=0;i<dateAfterSplit.length;i++)
                       System.out.print(dateAfterSplit[i]+" ");
      }
}

运行结果:2008 09 10          //结果为分割后的3个字符串

实例:
TestString1.java:
程序代码
public class TestString1
{
    public static void main(String args[]) {
        String s1 = "Hello World" ;
        String s2 = "hello world" ;
        System.out.println(s1.charAt(1)) ;
        System.out.println(s2.length()) ;
        System.out.println(s1.indexOf("World")) ;
        System.out.println(s2.indexOf("World")) ;
        System.out.println(s1.equals(s2)) ;
        System.out.println(s1.equalsIgnoreCase(s2)) ;

String s = "我是J2EE程序员" ;
        String sr = s.replace(‘我‘,‘你‘) ;
        System.out.println(sr) ;
    }
}

TestString2.java:
程序代码

public class TestString2
{
    public static void main(String args[]) {
        String s = "Welcome to Java World!" ;
        String s2 = "   magci   " ;
        System.out.println(s.startsWith("Welcome")) ;
        System.out.println(s.endsWith("World")) ;
        String sL = s.toLowerCase() ;
        String sU = s.toUpperCase() ;
        System.out.println(sL) ;
        System.out.println(sU) ;
        String subS = s.substring(11) ;
        System.out.println(subS) ;
        String s1NoSp = s2.trim() ;
        System.out.println(s1NoSp) ;
    }

String类主要方法的使用:

1、获取长度 *.length();//这与数组中的获取长度不同,*.length;

2、比较字符串(1) equals() //判断内容是否相同

(2)compareTo() //判断字符串的大小关系

(3)compareToIgnoreCase(String int) //在比较时忽略字母大小写

(4)==   //判断内容与地址是否相同

(5)equalsIgnoreCase() //忽略大小写的情况下判断内容是否相同

如果想对字符串中的部分内容是否相同进行比较,可以用

(6)reagionMatches() //有两种 public boolean regionMatches(int toffset, String other,int ooffset,int len);表示如果String对象的一个子字符串与参数other的一个子字符串是相同的字符序列,则为true.要比较的String 对象的字符串从索引toffset开始,other的字符串从索引ooffset开始,长度为len。

public boolean reagionMatches(boolean ignoreCase,int toffset,String other,int ooffset,int len);//用布尔类型的参数指明两个字符串的比较是否对大小写敏感。

一、查找字符串中某个位置的字符

public char charAt(int index);//返回指定索引index位置上的字符,索引范围从0开始

四、查找指定字符串在字符串中第一次或最后一词出现的位置

在String类中提供了两种查找指定位置的字符串第一次出现的位置的方法

(1)public int indexOf(String str);//从字符串开始检索str,并返回第一次出现的位置,未出现返回-1

(2)public int indexOf(String str,int fromIndex);//从字符串的第fromIndex个字符开始检索str

查找最后一次出现的位置有两种方法

(1)public int lastIndexOf(String str);

(2)public int lastIndexOf(String str,int fromIndex);

如果不关心字符串的确切位置则可使用public boolean contains(CharSequence s);

二、检查字符串的起始字符和结束字符

开始的字符串两种方法

(1)public boolean starWith(String prefix,int toffset);//如果参数prefix表示的字符串序列是该对象从索引toffset处开始的子字符串,则返回true

(2)public boolean starWith(String prefix);

结束的字符串方法

public boolean endsWith(String suffix);

三、截取子串

(1)public String subString(int beginIndex);

(2)public String subString(int beginIndex,int endIndex);//返回的字符串是从beginIndex开始到endIndex-1的串

要返回后4位可以这样写Syetem.out.println(*.subString()(*.length()-4));

四、字符串的替换

两种方法

(1)public String replace(char oldChar,char newChar);

(2)public String replace(CharSequence target,CharSequence replacement);//把原来的etarget子序列替换为replacement序列,返回新串

(3)public String replaceAll(String regex,String replacement);//用正则表达式实现对字符串的匹配

五、字符串的大小写替转换

(1)public String toLowerCase(Locale locale);

(2)public String toLowerCase();

(3)public String toupperCase(Locale locale);

(4)public String toUpperCase();

六、去除字符串首尾空格

*.trim();

七、字符串转换

1、将字符串转换成字符数组

public char[] toCharArray();

2、将字符串转换成字符串数组

public String[] split(String regex);//regex 是给定的匹配

3、将其它数据类型转化为字符串

(1)public static String valueOf(boolean b);

(2)public static String valueOf(char c);

(3)public static String valueOf(int i);

(4)public static String valueOf(long i);

(5)public static String valueOf(float f);

(6)public static String valueOf(double d);

(7)public static String valueOf(char[] data);

(8)public static String valueOf(Object obj);

可变字符串的创建和初始化

两种方法:

public StringBuffer();

public StringBuffer(int caoacity);

StringBuffer类主要方法的使用:

一、获取可变字符串长度

(1)public int length();

(2)public int capacity();

(3)public void setLength(int newLength);

二、比较可变字符串

用String 类的equals()方法比较,但是不同。

类Object中的equals()方法比较的是两个对象的地址是否相等,而不仅仅是比较内容,但是String类在继承Object类的时候重写了equals()方法,只是比较两个对象的内容是否相等

而在StringBuffer类中没有重写Object类的equals()方法,所以比较的是地址和内容。

三、追加和插入字符串

(1)追加 public StringBuffer append(type t);

(2)插入 public StringBuffer insert(int offset,type t);//在offset处加入类型为type的字符串

四、反转和删除字符串

(1)反转 public StringBuffer reverse();

(2)删除 public StringBuffer delete(int start,int end);

五、减少用于可变字符序列的存储空间

public void trimToSize();

六、StringBuffer类转换成String类

public String toString();

时间: 2024-08-26 01:31:48

android——字符串string(转)的相关文章

android 字符串string

String : 字符串类型 http://www.open-open.com/lib/view/open1387942832078.html 一.构造函数     String(byte[ ] bytes):通过byte数组构造字符串对象.     String(char[ ] value):通过char数组构造字符串对象.     String(Sting original):构造一个original的副本.即:拷贝一个original.     String(StringBuffer bu

Android字符串格式化开源库phrase介绍

在上一篇博客Android通过String.format格式化(动态改变)字符串资源的显示内容中介绍了通过String.format来格式化string.xml文件中的字符串,本文介绍一个可以实现同样功能的开源库phrase,相比于String.format,通过phrase格式化字符串代码更具可读性. 一.phrase项目介绍: 1.源码:phrase项目的源代码很简单,里面总共只有一个类:Phrase.java,代码如下: /* * Copyright (C) 2013 Square, In

Android字符串及字符串资源的格式化

为什么要写这一篇随笔呢?最近做项目的过程中,遇到很多页面在要显示文本时,有一部分是固定的文本,有一部分是动态获取的,并且格式各式各样.一开始采取比较笨的办法,把他拆分成一个个文本控件,然后对不同的控件采用不同的样式.这样做效率 很低,并且文本之间的对齐是个很大的问题,后来到网上寻求帮助,找到一些有关Android字符串和字符串资源格式化的文章,在此做一个总结. 一,字符串格式化 Java的String类给我们提供了两个重载的格式化字符串的方法,可以通过占位符的方式,向固定字符串中传入参数.他们分

Android R.string

在项目中代码中尽可能少出现中文(注释除外),对此,就需要将字符串设置到string.xml中 通常用法EXAMPLE 1:    string.xml中配置:<string name="hello">Hello!</string>    layout xml中使用方式为:<TextView                                android:layout_width="fill_parent"         

android获取string.xml的值

转自 http://blog.sina.com.cn/s/blog_618199e601011bst.html 为什么需要把应用中出现的文字单独存放在string.xml文件中呢? 一:是为了国际化,当需要国际化时,只需要再提供一个string.xml文件,把里面的汉子信息都修改为对应的语言(如,English),再运行程序时,android操作系统会根据用户手机的语言环境和国家来自动选择相应的string.xml文件,这时手机界面就会显示出英文.这样做国际化非常的方便. 二:为了减少应用的体积

Android字符串中使用占位符

一是可以通过Java的 String.format(String format, Object... args) 方法来实现 二则是通过Android自带的 getResources().getString(int id, Object... formatArgs) 实现 占位符的语法可以参考Java文档 简单演示下第二种方法 strings.xml 1 <string name="boolean_conversion">Boolean: %1$b\n</string

android获取string.xml的值(转)

为什么需要把应用中出现的文字单独存放在string.xml文件中呢? 一:是为了国际化,当需要国际化时,只需要再提供一个string.xml文件,把里面的汉子信息都修改为对应的语言(如,English),再运行程序时,android操作系统会根据用户手机的语言环境和国家来自动选择相应的string.xml文件,这时手机界面就会显示出英文.这样做国际化非常的方便. 二:为了减少应用的体积,降低数据的冗余.假设在应用中要使用"我们一直在努力"这段文字1000次,如果在每次使用时直接写上这几

Android字符串在strings.xml文件的定义和使用

路径:res/values/strings.xml 定义示例: 1 <resources> 2 <string name="app_name">SzLib</string> 3 <string name="address">广东省深圳市福田区福中一路2001号</string> 4 <string name="website">https://www.szlib.org.cn

C++中字符数组和字符串string

字符数组 C++中字符数组用char str[]可以用来表示一个字符串. (1)   数组的大小和字符串的长度. 数组的大小一定要大于字符串的长度,因为系统会自动补上一个'\0'作为字符串的结束标志.当然对于未初始化的也补'\0'. #include <iostream> #include <string> using namespace std; int main() { char str[11] = "I am happy"; // 系统会自动补上'\0'空