首页 > 编程语言 > 详细

Java中String的常用方法

时间:2016-09-23 11:15:15      阅读:210      评论:0      收藏:0      [点我收藏+]

开发中涉及到大量的对String的处理,熟练掌握String的常用方法,可以提高开发效率。

 

1. 字符与字符串,常用的方法有:

  • public String(char[] value)
  • public String(char[] value, int offset, int count)
  • public char charAt(int index)
  • public char[] toCharArray()
{
    //public char charAt(int index)
    //取出指定索引的字符
    String str = "hello";
    char c = str.charAt(1);
    System.out.println(c);
}

{
    //public char[] toCharArray()
    //字符数组与字符串的转换 
    String str = "hello";
    char[] strInCharArray = str.toCharArray();
    for(char item : strInCharArray)
    {
        System.out.print(item + " ");
    }
    System.out.println();
}

{
    //public char[] toCharArray()
    //判断一个给定的字符串是否有数字组成
    String str = "13212A355565";
    char[] strInCharArray = str.toCharArray();
    boolean flag = true;
    for(char item : strInCharArray)
    {
        if(item < ‘0‘ || item > ‘9‘)
        {
            flag = false;
            break;
        }
    }
    
    System.out.print(str + ": ");
    if(flag)
    {
        System.out.println("全部由数字组成!");
    }
    else
    {
        System.out.println("不是全由数字组成!");
    }
}

2. 字节与字符串

  • String(byte[] bytes)
  • String(byte[] bytes, int offset, int length)
  • public byte[] getBytes()
  • public byte[] getBytes(Charset charset)
//public byte[] getBytes()
//字符串与字节数组的转换
String str = "hello world";
byte[] strInBytes = str.getBytes();
for(byte item : strInBytes)
{
    System.out.println((int)item);
}

3. 字符串比较

  • public boolean equals(Object anObject)
  • public boolean equalsIgnoreCase(String anotherString)
String str1 = "hello";
String str2 = "HELLO";

System.out.println(str1.equals(str2));//false
System.out.println(str1.equalsIgnoreCase(str2));//true

4. 字符串查找

  • public boolean contains(CharSequence s)
  • public int indexOf(String str)
  • public int indexOf(String str, int fromIndex)
  • public int lastIndexOf(String str)
  • public int lastIndexOf(String str, int fromIndex)
  • boolean startsWith(String prefix)
  • public boolean startsWith(String prefix, int toffset)
  • public boolean endsWith(String suffix)
String str = "hello world";
System.out.println(str.indexOf("world"));
System.out.println(str.indexOf("l"));
System.out.println(str.indexOf("l",5));
System.out.println(str.lastIndexOf("l"));

 

Java中String的常用方法

原文:http://www.cnblogs.com/kuillldan/p/5898880.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!