您的位置:首页 > 编程语言 > Java开发

Java2入门与实例教程笔笔记-字符串处理,数组,异常处理

2008-07-22 09:23 417 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/hata_in_sweety/article/details/2688115

1           字符串处理

1.1            生成字符串

String sub = new String() / String(char subs[]) / String(char subs[], int startIndex, int numChars);

StringBuffer() /  StringBuffer(int strLen) /  StringBuffer(String sub);

字符串常量:双括号。Java编译器自动为字符串常量生成string类实例,可以直接初始化

1.1.1       Char str[] = {“g”,”d”};

String subStr = new String(str);

1.1.2       String  str1 = new String(“good”);

1.1.3       String  str3 = “good”;

1.1.4       StringBuffer str2 = new StringBuffer(“good”);

1.2            访问字符串:获得字符长度,某个字符或子串得索引位置,得到置顶的字符或子串。

length(), charAt(int index),  indexOf(int subchar/String subStr int fromIndex); lastIndexOf(same); getChar()

1.2.1       index: 0到字符串长度-1

1.2.2       capacity()和length()方法的区别。

1.3            修改字符串

1.3.1       toLowerCase() toUpperCase():大小写

1.3.2       replace(char oChar, char nChar);nchar代替ochar.

1.3.3       substring(int beginIndex) substring(int beginIndex, int endIndex):获得指定范围内子串

1.3.4       concat(String otherStr) 两字符串合并

// StringBuffer

1.3.5       setCharAt(int index, char subChar):设定指定位置字符

1.3.6       append(String str):末尾添加str字符串;

1.3.7       insert(int offset, String str):在offset位置插入str字符串

1.3.8       startsWith(String preStr)和endsWith(String endStr); 字符串的起始和终止子串是否与参数相同,返回值布尔型。

1.3.9       StartsWith(String preStr, int offsetInd):offsetInd位置开始是否存在preStr相同子串,布尔型

1.3.10    equals()和equalsIgnoreCase():比较两字符串是否相同,布尔型

1.3.11    compareTo(String otherString)和compareToIgnoreCase(String otherString);比较给定字符串和参数字符串的大小,返回值整形:0-相同,《0,参数字符串大于给定字符串》0,相反。

1.3.12    regionMatches(boolean igoreCase, int toffset, String other, int ooffset, int len)和regionMatches(int toffset, String other, int ooffset, int len): 比较当前字符串和参数字符串指定区域的子串是否相同。toffset, ooffset指明当前字符串和参数字符串other中进行比较的子串的起始索引位置,len指定比较的子串长度,ignoreCase指明是否区分大小写,后一种是区分大小写比较的

1.3.13    trim(): 删除给定字符串首尾的空格

StringBuffer可变字符串,可分配已超出缓冲区的空间,也可修改字符串,String不行

//5.1 strGen

public class strGen {

    char subchar1[] = {'g', 'o', 'o', 'd'};

    String subStr1 = new String(subchar1);

    char subchar2[] = {'w', 'e', 'e', 'l'};

    String subStr2 = new String(subchar2,1,2);

    StringBuffer subStr3 = new StringBuffer("good");

    String subStr4 = new String("good");

    public static void main(String[] args) {

        strGen strObject = new strGen();

System.out.println(strObject.subStr1+"/n"+strObject.subStr2+"/n"+strObject.subStr3+"/n"+strObject.subStr4+"/n");

    }

}

//5.2 strAcce

public class strAcce {

    String subStr = "this is a question about accessing string.";

    int strLen = subStr.length();

    char strChar = subStr.charAt(8);

    int strAt = subStr.indexOf('a');

    int strLastAt = subStr.lastIndexOf('a');

    int strSubAt = subStr.indexOf("ing");

    int strSubLastAt = subStr.lastIndexOf("ing");

    int char16a = subStr.indexOf('a', 15);

    int char16ba = subStr.lastIndexOf('a', 15);

    int str16ing = subStr.indexOf("ing", 15);

    int str16Lasting = subStr.lastIndexOf("ing", 15);

    char[] parStr = new char[8];

    public void getStr(){

        subStr.getChars(11, 15, parStr, 0);

    }

    public static void main(String[] args) {

        strAcce strObject = new strAcce();

        strObject.getStr();

        String newStr = new String(strObject.subStr);

        System.out.println("String:"+strObject.subStr);

        System.out.println("length of string:"+strObject.strLen);

        System.out.println("the index 8 is:"+strObject.strChar);

        System.out.println("the a first spot is:"+strObject.strAt);

        //System.out.print(strObject.subStr);

    }

}

//5.2.2 clDiff

public class cldiff {

    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("hero");

        int strLen = str.length();

        int strCap = str.capacity();

        System.out.println(strLen);

        System.out.println(strCap);// TODO code application logic here

    }

}

//5.3.1 strModify

public class strModify {

    public static void main(String[] args) {

        String str = "I will be there always";

        String strC= str.toLowerCase();

        String strCa= str.toUpperCase();

        String strR = str.replace("there", "here");

        String strS = str.substring(2, 9);

        String strCo = str.concat(" with you!");


      

        System.out.print("Source string is: "+str+"/n");

        System.out.print("The lowercase is: "+strC+"/n");

        System.out.print("The Uppercase is: "+strCa+"/n");

        System.out.print("The replace is: "+strR+"/n");

        System.out.print("The substring is: "+strS+"/n");

        System.out.print("The concat is: "+strCo);

    }

}

//5.3.5 strBuffer

public class strModifyBuffer {

    public static void main(String[] args) {

       StringBuffer str = new StringBuffer("I will be there with you");

       System.out.println("The source string is "+str+"/n");

       char chr = 'h';

       String strAp = "long";

       str.setCharAt(10, chr);

       System.out.println("The setCharAt is " + str + "/n");

       System.out.println("The append is " + str.append(strAp));

       System.out.println("The insert is " + str.insert(3, strAp));

        }

}

//5.3.9 strOthers

public class strOther {

    public static void main(String[] args) {

        String str = "  this is an test of other string  ";

        String pStr = "this";

        String eStr = "uhis";

        System.out.println("The source string is "+ str+ "/n");

        System.out.println("The startwith is "+ str.startsWith(pStr, 3)+"/n");

        System.out.println("The endwith is "+ str.endsWith(eStr)+"/n");

        System.out.println("The equals is "+ pStr.equalsIgnoreCase(eStr)+"/n");

        System.out.println("The compareto is "+ pStr.compareToIgnoreCase(eStr)+"/n");

        System.out.println("The regionMatch is "+ pStr.regionMatches(false, 1, eStr, 1, 2)+"/n");

        System.out.println("The trim string is "+ str.trim());

        // TODO code application logic here

    }

} 1           数组

数组是有序数据的集合,用统一的数组名和下标唯一确定数组中的元素,每个元素具有相同的数据类型,分为一维数组和多维数组。

1.1            一维数组:定义,初始化和引用

1.1.1       定义

type arrayName[];   /    type[] arrayName;

[]表明是数组类型变量,定义时并不为数组元素分配内存,所以不用给出数组长度,[]不用给出元素个数。

1.1.2       初始化

1.1.2.1       静态初始化:定义同时对数组元素初始化: String strName[] = {“how”,”are”,”you”}

1.1.2.2       动态初始化:

1.1.2.2.1        简单类型数组动态初始化:arrayName = new type[arraySize]

定义一个字符数组,并为该数组分配12个CHAR型数据空间:

char[] charName = new char[12] / char[charNum] //变量动态分配

1.1.2.2.2        复杂数据类型数组动态初始化:

String arrayName[];

arryaName = new String[5];

arryaName[0] = new String(“This”):

…..

arryaName[4] = new String(“arm”);

1.1.3       数组的引用

arrayName[index],index整,变和表达式;0-长度-1;越界检查,属性length长度即个数。

//数据的定义,初始化,引用

public class myArray {

    public static void main(String[] args) {

        int[] intStr1 = new int[5];

        for(int i=0;i<5;i++){

            intStr1[i] = i*2;

        System.out.println("intStr["+i+"] = "+intStr1[i]+"/n");

        }

        System.out.println("****************");

        int arrLen = 4;

        int[] intStr2 = new int[arrLen];

        for(int j=intStr2.length-1;j>=0;j--){

        //for(int j=0; j<intStr2.length;j++){

            intStr2[j] = j+3;

            System.out.println("intStr["+j+"] = "+intStr2[j]+"/n");

        }

       String[] str = {"how", "are", "you"};

       System.out.println(str[0]+str[1]+str[2] );

        // TODO code application logic here

    }

}


1.1            多维数组

1.1.1       定义: type arrayName[][];  type[] arrayName[];  type[][] arrayName; 定义时不分配空间。

1.1.2       初始化:每一维不必相同大小

1.1.2.1       静态初始化(定义时分配空间):int Array[][] = {{1,1},{2.2.2}};

1.1.2.2       动态初始化: 1.arrayName = new type[arrayLength][arrayLength2];

2 arrayName = new type[arrayLen1][]; (最高维度开始)

                                   arrayName[0] = new type[arrayLen20];

                                   arrayName[1] = new type[arrayLen21];

1.1.3       引用:arrayName[index1][index2]

public static void main(String[] args) {

        int i, j, k;

        int a[][] = new int[3][3];

        int b[][] = new int[3][3];

        int c[][] = new int[3][3];

        int d[][] = new int[3][3];

        int e[][] = new int[3][3];

        int f[][] = new int[3][3];

        for(i=0; i<3; i++)

        {

          for(j=0; j<3; j++)

          {

              a[i][j] = (int)(i+j);

              b[i][j] = (int)(i*j);

          }

        }

        for (i=0; i<3; i++)

        {

            for(j=0; j<3; j++)

            {

                c[i][j] = (int)(a[i][j]+b[i][j]);

                d[i][j] = (int)(a[i][j]-b[i][j]);

                e[i][j] = (int)(a[i][j]*b[i][j]);

            }

        }

        for(i=0; i<3; i++)

        {

            for(j=0; j<3; j++)

            {

                f[i][j] = 0;

                for(k=0; k<3; k++)

                    f[i][j]+=(int)(a[i][k]*b[k][j]);

            }

        }

        System.out.println("/nMatrix A:");

        for(i=0; i<3; i++)

        {

            for(j=0; j<3; j++)

                System.out.print(a[i][j]+" ");

            System.out.println();

        }

        System.out.println("/nMatrix B:");

        for(i=0; i<3; i++)

        {

            for(j=0; j<3; j++)

                System.out.print(b[i][j]+" ");

        }

        System.out.println("/nMatrix C:");

        for(i=0; i<3; i++)

        {

            for(j=0; j<3; j++)

                System.out.print(c[i][j]+" ");

            System.out.println();

        }

       System.out.println("/nMatrix D:");

        for(i=0; i<3; i++)

        {

            for(j=0; j<3; j++)

                System.out.print(d[i][j]+" ");

            System.out.println();

        }

       System.out.println("/nMatrix E:");

        for(i=0; i<3; i++)

        {

            for(j=0; j<3; j++)

                System.out.print(e[i][j]+" ");

            System.out.println();

        }

             System.out.println("/nMatrix F:");

        for(i=0; i<3; i++)

        {

            for(j=0; j<3; j++)

                System.out.print(f[i][j]+" ");

            System.out.println();

        } // TODO code application logic here

}

1           异常处理

1.1            概念

l          异常(事件):异常事件,中断指令运行。对应异常对象亦分两类

l          抛出异常:异常产生和提交过程,关键字“throw”实现抛出Throwable类或子类实例。

l          异常捕获:异常对象交给寻找到的方法进行处理,关键字“try-catch-finally”

try{

throw new Exception(“Throw Exception”);

***//捕获异常的范围,可能会产生异常对象并抛出

}catch (ExceptionName1 exceptionObject){

***处理try代码块生辰的异常事件,catch多个,带参数,指明能够捕获的异常类型,必须是Throwable子类,程序运行时,系统通过参数把被抛出的异常对象传递给catch代码块

}

}catch (ExceptionName1 exceptionObject){

***

}

***

finally{

***统一出口,都会被执行。

}

l          异常对象:对应Throwable类和子类,JAVA虚拟机,类的实例,程序生成。

l          java.lang.Error:虚拟机错误,不会捕获,抛出。

l          java.lang.Exception:程序处理。

l          处理机制:异常事件-生成异常对象(异常事件类型,程序运行状态信息)-对象传递给系统-寻找处理异常的代码(生成异常对象的代码块开始寻找-对方法的调用栈逐层回溯-找到处理异常的方法)-异常对象交给寻找到的方法进行处理(异常捕获)-如无,系统终止运行。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: