• JAVA基础--常用类 String,StringBuffer, 基础数据类型包装类, Math类, Enum类


    • 字符串相关类: String, StringBuffer

    String类为不可变的字符序列

    String s1="hello";
    String s2="hello";
    System.out.println(s1==s2); //true
    
    s1=new String("hello");
    s2=new String("hello");
    System.out.println(s1==s2); //false
    System.out.println(s1.equals(s2)); //true
    
    
    char c[]={'s','u','n','  ', 'j','a','v','a'};
    String s4=new String(c);
    String s5=new String(c,4,4);
    System.out.println(s4); // sun java
    System.out.println(s5); //java
    

    String类常用方法:

    public class Test{
         public static void main(String[] args){
              String s1="sun java", s2="sun Java";  
              System.out.println(s1.charAt(1));  //s
              System.out.println(s1.length()); //8
              System.out.println(s1.indexOf("java")); //4
              System.out.println(s1.indexOf("Java")); //-1
              System.out.println(s1.equals(s2)); //false
              System.out.println(s1.equalsIgnoreCase(s2)); //true
    
               String s="我是程序员,我在学java";
                String sr=s.replace("我","你");
                System.out.println(sr); //你是程序员, 你在学java
        }  
    }                
    

      

    public class Test{
         public static void main(String[] args){
              String s="Welcome to Java World!";
              String s1=" sun java ";
       
              System.out.println(s.startsWith("Welcome"));  //true
              System.out.println(s.endsWith("World"));  //false
              
              String sL=s.toLowerCase();
              String sU=s.toUpperCase();
              System.out.println(sL);  // Welcome to Java World!
              System.out.println(sU);  // WELCOME TO JAVA WORLD!
    
              String subS=s.substring(11);
              System.out.println(subS);  // Java World!
              String sp=s1.trim();
              System.out.println(sp); //sun java
            
        }  
    }           
    

      

    String类还有个静态重载方法 public static String valueOf(Object obj); 用于把obj转换成String类型. 如果是对象, 是通过toString方法来转换.

    public String[] split(String regex): 将一个字符串按照指定的分隔符分隔, 返回分割后的字符串数组.

    public class Test{
         public static void main(String[] args){
              int j=1234567;
              String sNumber=String.valueOf(j);  //int转换成String
       
              System.out.println("j是"+sNumber.length()+"位数");  //7
             
              String s="Mary, F, 1976";
              String[] sPlit=s.split(",");
              for(int i=0;i<sPlit.length;i++)
                  System.out.println(sPlit(i));  // Mary
                                                 //F
                                                 //1976
        }  
    }           
    

     

    一个字符串里有多少个大写字母,多少个小写字母,多少个其他字符:

    public class TestStringCase {
    	public static void main(String[] args) {
    		String s = "ABAabb$&^$#BAAb898B#@%aa";
    		int cU = 0, cL = 0, cO = 0;
    		for(int i=0; i<s.length(); i++) {
    			char c = s.charAt(i);
    			
    			if(c >= 'A' && c <= 'Z') {                    //if(Character.isLowerCase(c))
    				cU ++;
    			} else if( c >= 'a' && c <='z') {             //if(Character.isUpperCase(c))  
    				cL ++;
    			} else {
    				cO ++;
    			}
    		}
    		
    		System.out.println("大写:" + cU);
    		System.out.println("小写:" + cL);
    		System.out.println("其他:" + cO);
    	}
    }
    

     

    一个字符串里有多少个java:

    public class TestStringCase {
    	public static void main(String[] args) {
    		String s = "sunjavahpjavaokjavajjavahahajavajavagoodjava";
                    String sToFind="java";
                    int count = 0;
                    int index=-1;
                  
    		while((index=s.indexOf(sToFind))!=-1){ 
                s=s.substring(index+sToFind.length());
                count++;
             }
             System.out.println(count);
    }
    }

    StringBuffer类:

    String类是不可变的字符序列, 比如

    可以实现, 但是内存是这样处理的, 

    先开辟一段新的 "hello"空间, 再创建一个"world" 空间, 最后再创建一个新的空间用于s1+s2, 然后s1重新指向新的连接的空间.

    这样对内存是一种浪费.

    String s1="hello";
    String s2="world";
    s1+=s2; // hello world
    

    所以用StringBuffer类替代:

    添加字符用append()方法:

    还可以使用的方法: insert(int offset, String str), indexOf(), substring(), length(), reverse()

    public class TestStringCase {
    	public static void main(String[] args) {
    		String s = "Microsoft";
              char[] a={'a','b','c'}; StringBuffer sb1=new StringBuffer(s);
              sb1.append('/').append("IBM").append('/').append("sun");
              System.out.println(sb1); //Microsoft/IBM/sun
              StringBuffer sb2=new StringBuffer("数字");
    for(int i=0;i<=9;i++){sb2.append(i);}
    System.out.println(sb2); //数字0123456789
    sb2.delete(8,sb2.length()).insert(0,a); //从第8个截取到最后, "数字012345", 然后第0位置把a数组插进去
    System.out.println(sb2); // abc数字0123456
    System.out.println(sb2.reverse()); //543210字数cba

    }

      

      

      

    基本数据类型包装类: Boolean, Character, Byte, Short, Integer, Long, Float, Double. 

    基本数据类型都存在栈上, 如果想包装成对象分配在堆上就使用基本数据类型的包装类.

    1. 对象转成基本类型

    Integer i=new Integer(100);

    int j=i.intValue();  //返回封装数据的int型值

    2. 字符串转成基本类型

    public static int parseInt(String s) throws NumberFormatException;  //字符串解析成int数据.

    3. 字符串转换成 基本类型对象

    public static Integer valueOf(String s) throws NumberFormatException;  字符串转换成Integer对象.

    所以parseInt= valueOf+intValue

    public class Test{
       public static void main(String[] args){
        Integer i=new Integer(100);
        Double d=new Double("123.456");
        int j=i.intValue()+d.intValue();
        float f=i.floatValue()+d.floatValue();
        System.out.println(j);
        System.out.println(f);
        double pi=Double.parseDouble("3.1415926"); //字符串转换成double类型的数
        double r=Double.valueOf("2.0").doubleValue(); //先将字符串2.0转换成Double对象, 然后再转换成double值
    double s=pi*r*r;
        System.out.println(s);
    try{
          int k=Integer.parseInt("1.25"); //字符串转int不可以.
        }catch(NumberFormatException e){
          System.out.println("数据格式不对");
        }
        System.out.println(Integer.toBinaryString(123)+"B");
        System.out.println(Integer.toHexString(123)+"H");
        System.out.println(Integer.toOctalString(123)+"O"); } }

    把"1,2;3,4,5;6,7,8" 分隔成double的数组 

    public class ArrayParser
    {
    	public static void main(String[] args) {
    		double[][] d;
    		String s="1,2;3,4,5;6,7,8";
    		String[] sFirst=s.split(";");
    		d=new double[sFirst.length][];
    		for(int i=0;i<sFirst.length;i++){
    			String sSecond=sFirst[i].split(",");
    			d[i]=new double[sSecond.length];
    			for(int j=0;j<sSecond.length;j++){				
    				d[i][j]=Double.parseDouble(sSecond[j]);
    			}
    		}
    		for(int i =0;i<d.length;i++){
    			for(int j=0;j<d[i].length;j++){
    				System.out.print(d[i][j]+" ");
    			}
    			System.out.println();
    		}
    
    	}
    }
    

      

    Math类: abs, sqrt, max, min,random, round, 

    File类: java.io.File类代表系统文件名(路径和文件名)

    构造方法: public File(String pathname);  

    静态属性: public static final String seperator

    package bjsxt;
    import java.io.*;
    public class TestFile {
      public static void main(String[] args) {
        String separator = File.separator;
        String filename = "myfile.txt";
        String directory = "mydir1" + separator + "mydir2";
        //String directory = "mydir1/mydir2";
        //String directory = "mydir1\mydir2";   //这种也可以, 但是放在linux下就出错了.
        File f = new File(directory, filename);
        if (f.exists()) {
          System.out.println("文件名:" + f.getAbsolutePath());
          System.out.println("文件大小:" + f.length());
        } else {
          f.getParentFile().mkdirs();
          try {
            f.createNewFile();
          } catch (IOException e) {
           e.printStackTrace();
          }
        }
      }
    }
    

    递归列出子目录:

    import java.io.*;
    
    public class ListFile {
    	public static void main(String[] args) {
    		File f = new File("d:\test");
    		/*
    		File[] files = f.listFiles();
    		for(File ff : files) {
    			System.out.println(ff.getName());
    		}
    		*/
    		listChilds(f, 0);
    	}
    	
    	public static void listChilds(File f, int level) {
    		
    		String preStr = "";
    		for(int i=0; i<level; i++) { preStr += "    "; }
    			
    		System.out.println(preStr + f.getName());
    		if(!f.isDirectory()) return;
    		File[] childs = f.listFiles();
    		for(int i=0; i<childs.length; i++) {
    				listChilds(childs[i], level + 1);
    		}
    	}
    }
    

      

      

    枚举类:java.lang.Enum

    public class TestEnum{
       public enum MyColor{red, green, blue};  
      public enum MyDoorOpener{me, mywife};
      public static void main(String[] args){
        MyColor m=MyColor.red;
    switch(m){
          case red:
            System.out.println("red");
            break;
    case green:
            System.out.println("green");
            break;
          default:
            System.out.println("default");
        }
        System.out.println(m);
      } }

     

     

  • 相关阅读:
    亲们,知道你想更优秀,你做到这些了吗?
    Linux socket编程学习笔记(一):socket()函数详解
    关于typedef的用法总结
    c,c++里面,头文件里面的ifndef /define/endif的作用
    玩转ptrace
    文笔流畅,修辞得体
    定义和实现一个类的成员函数为回调函数
    《Shell 脚本学习指南 》 背景知识与入门 [第一、二章]
    使用ptrace跟踪进程
    FCKeditor 2.6.4.1配置
  • 原文地址:https://www.cnblogs.com/wujixing/p/5345273.html
Copyright © 2020-2023  润新知