2013年1月4日 星期五

Java 字串 String API 用法大全

0

Java 字串 String API 用法大全

 String是一個比較特別的資料型態,它是一個物件類別( Object ),基本型態所對應的物件類別,可直接給於相同類型的值,而不需使用new來產生物件,而String資料型態跟基本型態一樣可以直接給於值,不過String沒有相對應的基本型態。 String在使用上十分普遍,大部份的資料型能都可以變成String存放。String本身是字串是使用utf8格式存放的,所以在計算字元時,一個中文字跟一個英文字都是算1,這點是跟其它程式語言不太一樣的。

 String的宣告及初始化 “ ”雙引號內資料則為String資料型能

#

 //直接給值
            String a = "123";
            System.out.println("a:"+a);
 
            //new 一個String物件
            String b = new String("456");
            System.out.println("b:"+b);
 
            //先宣告再給值
            String c ;
            c = "789";
            System.out.println("c:"+c);
 
            //先宣告再new一個物件
            String d;
            d = new String("321");
            System.out.println("d:"+d);


字串的連結合併 字串的連結合併是利用 + 來使二個字串變成一個字串
#
         String z = a + b;//二字串變數相加,連結
            System.out.println("二字串變數相加:"+z);
 
            String y = "789"+"123";//二字串相加,連結
            System.out.println("二字串相加:"+y);
 
            String x = 456+"123" ;//數字加字串,連結
            System.out.println("數字加字串:"+x);
String.valueOf 基本型態轉換成字串 利用靜態函數String.valueOf(型態)可以把型能轉變成字串
#

 int num = 123;
        String Snum = String.valueOf(num);
        System.out.println("數字變字串:"+Snum);
        //數字變字串:123
 
        double numf = 123.1;    
        String Snumf = String.valueOf(numf);
        System.out.println("浮點變字串:"+Snumf);
        //浮點變字串:123.1

基本型態物件.parse基本型態 字串轉換成基本型態 利用基本型態物件的函數parse,可以把字轉換成基本型態,如果無法轉換時會有Exception產生
#

 String Sint = "123";
        int myint = Integer.parseInt(Sint);
        System.out.println("字串轉換成數字:"+myint);
        //字串轉換成數字:123
 
        String SFloat = "123.1";
        float myfloat= Float.parseFloat(SFloat);
        System.out.println("字串轉換成浮點數:"+myfloat);
        //字串轉換成浮點數:123.1
 
        String SDouble = "123.2";
        double mydouble= Double.parseDouble(SDouble);
        System.out.println("字串轉換成雙浮點數:"+mydouble);
        //字串轉換成雙浮點數:123.2
 
        //其它型態以此類推...

IndexOf 查詢字元位存在於字串內位置,以0為起始 IndexOf(字串),有找到字串時會回傳第一個字元的位置,IndexOf如查詢不到,則會回傳-1 字串內的內容存放可視為一連續空間,而每一個字元均存放在順序的位置上,如下表所示:
#

 String smart = "Smart";
        int idx = smart.indexOf("m");
        System.out.println("m所在位置:"+idx);
        //m所在位置:1
 
        idx = smart.indexOf("rt");
        System.out.println("rt所在位置:"+idx);
        //rt所在位置:3
 
        idx = smart.indexOf("z");
        System.out.println("z所在位置:"+idx);
        //z所在位置:-1
 
        //中文部份
        String chinese = "中華民國";
        int cidx = chinese.indexOf("民");
        System.out.println("民所在位置:"+cidx);
        //民所在位置:2
 
        cidx = chinese.indexOf("中華");
        System.out.println("中華所在位置:"+cidx);
        //中華所在位置:0
 
        cidx = chinese.indexOf("台灣");
        System.out.println("台灣所在位置:"+cidx);
        //台灣所在位置:-1

replaceAll、replaceFirst字串取代 replaceAll (要被取代的字串,要取代的字串) 取代全部找到的”要被取代字串” replaceFirst (要被取代的字串,要取代的字串) 取代第一個找到的”要被取代字串” 其中replaceAll函數可以使用正規表示式來做整批有規則性的取代
#

 String replaceString = "blog.yslifes.com,blog.yslifes.com";
        String replaced = replaceString.replaceAll("blog", "www");
        System.out.println("All取代後的字串:"+replaced);
        //All取代後的字串:www.yslifes.com,www.yslifes.com
 
        replaced = replaceString.replaceFirst("blog", "www");
        System.out.println("First取代後的字串:"+replaced);
        //First取代後的字串:www.yslifes.com,blog.yslifes.com

String.format字串格式化 String.format是一個靜態函數,可以直接使用,將字串依設定的位置或格式回傳出來。 如需顯示三位數的字串數字,前方補零,則可利用以下方法:
#

String formatStr = "%03d";
        String formatAns = String.format(formatStr, 12);
        System.out.println("數字補零:"+formatAns);
        //數字補零:012

CharAt取得指定字元 CharAt(位置)可取出指定位置的字元,中文算法與英文相同
#

String charStr = "This is my Web site! blog.yslifes.com";
        char c = charStr.charAt(3);
        System.out.println("英文第4位的字元是:"+c);
        //英文第4位的字元是:s
 
        charStr = "這是我的網站! blog.yslifes.com";
        c = charStr.charAt(5);
        System.out.println("中文第5位的字元是:"+c);
        //中文第5位的字元是:站

equals 二字串是否相等 equals可以比較二個字串或物件是否相同,以為Object原型就有的方法,字串要全數相同回傳值才會為true
#

  String aStr = "String A";
 
        String bStr = "String B";
        boolean Equal = aStr.equals(bStr);
        System.out.println("a與b是否相同:"+Equal);
        //a與b是否相同:false
 
        String cStr = "String A";
        Equal = aStr.equals(cStr);
        System.out.println("a與c是否相同:"+Equal);
        //a與c是否相同:true
 
        String dStr = "String A ";
        Equal = aStr.equals(dStr);
        System.out.println("a與d是否相同:"+Equal);
        //a與d是否相同:false

split字串切割 split(指定符號) ,可依指定符號把字串分開成陣列
#
String splitStr = "blog,yslifes,com";
        String[] array = splitStr.split(",");
        for(int i = 0 ; i < array.length ; i ++)
            System.out.println("第"+i+"個:"+array[i]);
        /*
        第0個:blog
        第1個:yslifes
        第2個:com
substring取得指定字串範圍 substring(起始值 , 終始值),可以取出起始位置,到終止位置的字串,其中包含起始值,不包含終始值
#
String subStr = "blog.yslifes.com";
        String sub1 = subStr.substring(1, 4);
        System.out.println("第1到4的字串內容為:"+sub1);
        //第1到4的字串內容為:log

trim去空白 trim()可以去除左邊及右邊二則空白,不過在字串間空白並不會處理
#

String HasEmptyStr = " ABC";
        System.out.println("1空白去除:"+HasEmptyStr.trim());
        //1空白去除:ABC
 
        HasEmptyStr = "ABC ";
        System.out.println("2空白去除:"+HasEmptyStr.trim());
        //2空白去除:ABC
        HasEmptyStr = " ABC ";
        System.out.println("3空白去除:"+HasEmptyStr.trim());
        //3空白去除:ABC
 
        HasEmptyStr = "ABC DEF";
        System.out.println("4空白去除:"+HasEmptyStr.trim());
        //4空白去除:ABC DEF

字串長度 length()可以取回字串的長度
#
String strLength = "長度是多少呢?";
        System.out.println("字串長度:"+strLength.length());
        //字串長度:7
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#format(java.lang.String, java.lang.Object...) http://blog.yslifes.com/archives/638

2012年12月17日 星期一

JSP裡的變量列表

0


JSP裡的變量列表

<%
out.println("Protocol: " + request.getProtocol() + " ");
out.println("Scheme: " + request.getScheme() + " ");
out.println("Server Name: " + request.getServerName() + " " );
out.println("Server Port: " + request.getServerPort() + " ");
out.println("Protocol: " + request.getProtocol() + " ");
out.println("Server Info: " + getServletConfig().getServletContext().getServerInfo() + " ");
out.println("Remote Addr: " + request.getRemoteAddr() + " ");
out.println("Remote Host: " + request.getRemoteHost() + " ");
out.println("Character Encoding: " + request.getCharacterEncoding() + " ");
out.println("Content Length: " + request.getContentLength() + " ");
out.println("Content Type: "+ request.getContentType() + " ");
out.println("Auth Type: " + request.getAuthType() + " ");
out.println("HTTP Method: " + request.getMethod() + " ");
out.println("Path Info: " + request.getPathInfo() + " ");
out.println("Path Trans: " + request.getPathTranslated() + " ");
out.println("Query String: " + request.getQueryString() + " ");
out.println("Remote User: " + request.getRemoteUser() + " ");
out.println("Session Id: " + request.getRequestedSessionId() + " ");
out.println("Request URI: " + request.getRequestURI() + " ");
out.println("Servlet Path: " + request.getServletPath() + " ");
out.println("Accept: " + request.getHeader("Accept") + " ");
out.println("Host: " + request.getHeader("Host") + " ");
out.println("Referer : " + request.getHeader("Referer") + " ");
out.println("Accept-Language : " + request.getHeader("Accept-Language") + " ");
out.println("Accept-Encoding : " + request.getHeader("Accept-Encoding") + " ");
out.println("User-Agent : " + request.getHeader("User-Agent") + " ");
out.println("Connection : " + request.getHeader("Connection") + " ");
out.println("Cookie : " + request.getHeader("Cookie") + " ");
out.println("Created : " + session.getCreationTime() + " ");
out.println("LastAccessed : " + session.getLastAccessedTime() + " ");

%>

运行结果:

Protocol: HTTP/1.1
Scheme: http
Server Name: 192.168.0.1
Server Port: 8080
Protocol: HTTP/1.1
Server Info: JavaServer Web Dev Kit/1.0 EA (JSP 1.0; Servlet 2.1; Java 1.2; Windows NT 5.0 x86; java.vendor=Sun Microsystems Inc.)
Remote Addr: 192.168.0.106
Remote Host: abc
Character Encoding: null
Content Length: -1
Content Type: null
Auth Type: null
HTTP Method: GET
Path Info: null
Path Trans: null
Query String: null
Remote User: null
Session Id: To1010mC466113890241879At
Request URI: /c.jsp
Servlet Path: /c.jsp
Accept: */*
Host: 192.168.0.1:8080
Referer : null
Accept-Language : zh-cn
Accept-Encoding : gzip, deflate
User-Agent : Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)
Connection : Keep-Alive
Cookie : SESSIONID=To1010mC466113890241879At
Created : 965764522168
LastAccessed : 965775587088。

2012年12月14日 星期五

JSP Page 指令

0


JSP Page 指令

內容、字碼設定
<%@ page contentType="text/html;charset=big5" %>
引入套件
<%@ page import="java.util.*" %>
指定錯誤處理頁面
<%@ page errorPage="error.jsp" %>
定義這個網頁是錯誤處理頁面
<%@ page isErrorPage="true" %>
網頁編碼的指定
<%@ page pageEncoding="big5" %>




2012年12月12日 星期三

Vector Example in java

0

In this example we are going to show the use of java.util.Vector class. We will be creating an object of Vector class and performs various operation like adding, removing etc. Vector class extends AbstractList and implements List, RandomAccess, Cloneable, Serializable. The size of a vector increase and decrease according to the program. Vector is synchronized. In this example we are using seven methods of a Vector class. add(Object o): It adds the element in the end of the Vector size(): It gives the number of element in the vector. elementAt(int index): It returns the element at the specified index. firstElement(): It returns the first element of the vector. lastElement(): It returns last element. removeElementAt(int index): It deletes the element from the given index. elements(): It returns an enumeration of the element In this example we have also used Enumeration interface to retrieve the value of a vector. Enumeration interface has two methods. hasMoreElements(): It checks if this enumeration contains more elements or not. nextElement(): It checks the next element of the enumeration. Code of this program is given below: //java.util.Vector and java.util.Enumeration; import java.util.*; public class VectorDemo{ public static void main(String[] args){ Vector vector = new Vector(); int primitiveType = 10; Integer wrapperType = new Integer(20); String str = "tapan joshi"; vector.add(primitiveType); vector.add(wrapperType); vector.add(str); vector.add(2, new Integer(30)); System.out.println("the elements of vector: " + vector); System.out.println("The size of vector are: " + vector.size()); System.out.println("The elements at position 2 is: " + vector.elementAt(2)); System.out.println("The first element of vector is: " + vector.firstElement()); System.out.println("The last element of vector is: " + vector.lastElement()); vector.removeElementAt(2); Enumeration e=vector.elements(); System.out.println("The elements of vector: " + vector); while(e.hasMoreElements()){ System.out.println("The elements are: " + e.nextElement()); } } } Output of this example is given below: C:\Java Tutorial>javac VectorDemo.java C:\Java Tutorial>java VectorDemo the elements of vector: [10, 20, 30, tapan joshi] The size of vector are: 4 The elements at position 2 is: 30 The first element of vector is: 10 The last element of vector is: tapan joshi The elements of vector: [10, 20, tapan joshi] The elements are: 10 The elements are: 20 The elements are: tapan joshi