美文网首页
String类的常用方法(字符与字符串)

String类的常用方法(字符与字符串)

作者: 落在牛背上的鸟 | 来源:发表于2018-03-04 11:03 被阅读38次

对于API文档,由以下几个部分组成:

  • 类的定义以及相关的继承结构;
  • 类的一些简短说明;
  • 类中的成员方法;
  • 类中所提供的构造方法;
  • 类中所提供的普通方法;
  • 成员、构造方法、普通方法的详细说明。

1. String类中常用的方法

No. 方法名称 类型 描述
1 public String(char[] value) 构造 将字符数组转换为String对象
2 public String(char[] value,int offset,int count) 构造 将部分字符数组转换为String
3 ublic char charAt(int index) 普通 返回指定索引对应的字符信息
4 public char[] toCharArray() 普通 将字符串以字符数组的形式返回

范例:取出指定索引的字符

public class StringIndex {
    public static void main(String[] args) {
        String input = "hello" ;
        char c = input.charAt(0);
        System.out.println(c);
    }
}

范例:字符串转换为字符数组

public class StringIndex {
    public static void main(String[] args) {
        String str = "hello" ;
        //将字符串转换为字符数组
        char[] data = str.toCharArray();
        for (int x = 0 ; x < data.length ; x++){
            System.out.println(data[x]);
        }
    }
}

范例:将小写转大写

public class StringIndex {
    public static void main(String[] args) {
        String str = "hello" ;
        //将字符串转换为字符数组
        char[] data = str.toCharArray();
        for (int x = 0 ; x < data.length ; x++){
            data[x] -= 32;
            System.out.print(data[x]);
        }
    }
}

范例:给定一个字符串,要求判断其时候由数字组成

public class StringIndex {
    public static boolean isNumber(String c){
        char[] data = c.toCharArray();
        for (int x = 0 ; x <data.length ; x++){
            if(data[x] > '9' || data[x] < '0'){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String str = "123456" ;
        if(isNumber(str)){
            System.out.println("字符串由数字组成");
        }else{
            System.out.println("字符串由非数字组成");
        }
    }
}

如果写的某一个方法返回的内容是boolean , 那么习惯型的做法是将其以"isXxx"的格式命名。

相关文章

网友评论

      本文标题:String类的常用方法(字符与字符串)

      本文链接:https://www.haomeiwen.com/subject/tgixfftx.html