示例代码:
字符串操作方法:
- class StringOps{
- public static void main(String args[]){
- String str1 = "hello java is important for u";
- String str2 = new String(str1);
- String str3 = "hello one two three four one";
- int dix,result;
- if(str1.equals(str2)){ //boolean equals(str) 相等返回true
- System.out.println("str1 equals str2");
- }else{
- System.out.println("str1 not equals str2");
- }
- System.out.println("str1的长度是:"+ str1.length()); //int length()返回字符串长度
- for(int i=0;i < str2.length();i++){
- System.out.print(str2.charAt(i)); //char charAt(index) 获取index位置的字符
- }
- System.out.println();
- result = str1.compareTo(str3); //int compareTo(str) 小于返回小于0的数,等于返回0,大于返回大于0的数
- if(result == 0){
- System.out.println("str1 与 str3相等");
- }else if(result < 0){
- System.out.println("str1 比 str3小");;
- }else{
- System.out.println("str1 比 str3大");;
- }
- dix = str3.indexOf("one"); //int indexOf(str) 查找字符串,返回第一个匹配的索引,没有匹配返回-1
- System.out.println("the first one is:"+ dix);
- dix = str3.lastIndexOf("one"); //int lastIndexOf(str)查找字符串,返回最后一个匹配的索引,没有返回-1
- System.out.println("the last one is:"+ dix);
- }
- }
-------------------------------------------------------------------------------------------------------------
字符串数组:
- class StringArrays{
- public static void main(String args[]){
- String[] str1 = {"hello", "java", "is", "important", "for", "u"}; //字符串数组
- System.out.println("origial:");
- for(String s : str1){ //for-each循环输出内容
- System.out.print(s+" ");
- }
- System.out.println();
- str1[2] = "was"; //修改元素
- str1[5] = "me";
- System.out.println("modified:");
- for(String s : str1){
- System.out.print(s+" ");
- }
- System.out.println();
- String str2 = str1.substring(6,20); //substring(int startindex,int endindex)返回指定部分字符串
- System.out.println(str1);
- System.out.println(str2);
- }
- }
------------------------------------------------------------------------------------------------------------------
用String控制switch语句:
- class StringSwitch{
- public static void main(String args[]){
- String command = "cancel";
- switch(command){ //switch()语句
- case "connect":{
- System.out.println("Connecting");
- break;
- }
- case "cancel":{
- System.out.println("Canceling");
- break;
- }
- case "disconnect":{
- System.out.println("DisConnecting");
- break;
- }
- default:{
- System.out.println("command error!");
- break;
- }
- }
- }
- }
-----------------------------------------------------------------------------
使用命令行实参:命令行执行java CLDemo one two three
- class CLDemo{
- public static void main(String args[]){
- System.out.println(args.length);
- for(int i=0;i < args.length;i++){
- System.out.println(args[i]);
- }
- }
- }