• String 處理 in Java


       String value = "this is a book!\n\nHello,world.";
       String[] paras = value.split("\n\n|,| |!|\\.");    
       for(int i=0;i<paras.length;i++)
         System.out.println(paras[i]);

    有人可能會想到 java.util.StringTokenizer,基本上API中明確的表示它已經是遺產類別(Legacy class)了,存在的原因是為了舊程式的相容性,不建議在您撰寫新程式時使用,使用split()來代替會是個好的方案,而且您還可以進一步 使用正則表示式 來進行字串分離。

    ref:http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html

    注意到了嗎?== 運算在Java中被用來比較兩個名稱是否參考至同一物件,所以不可以用==來比較兩個字串的內容是否相同,例如:

    String str1 = new String("caterpillar");
    String str2 = new String("caterpillar");
    System.out.println(str1 == str2);

     
    上面會顯示false的結果,因為str1與str2是分別參考至不同的字串物件,如果要比較兩個(字串)物件是否相同,您要使用equals()方法,例如:

    String str1 = new String("caterpillar");
    String str2 = new String("caterpillar");
    System.out.println(str1.equals(str2));


    這樣子結果才會顯示所想要的比較結果:true。

    1 如何将字串 String 转换成整数 int?  

    A. 有两个方法: 

    1). int i = Integer.parseInt([String]); 或  
    i = Integer.parseInt([String],[int radix]); 

    2). int i = Integer.valueOf(my_str).intValue();  

    注: 字串转成 Double, Float, Long 的方法大同小异.  


    2 如何将整数 int 转换成字串 String ?  


    A. 有叁种方法: 

    1.) String s = String.valueOf(i); 

    2.) String s = Integer.toString(i);  

    3.) String s = "" + i;  

    注: Double, Float, Long 转成字串的方法大同小异. 
  • 相关阅读:
    MyEclipse配置DataBase Explorer
    Eclipse 如何设置注释的模板
    游戏开发技术
    static_cast 与reinterpret_cast
    一个人的成功取决于晚上的8点至10点经典语录必读
    发送消息给线程
    转载ofstream和ifstream详细用法
    Effective STL笔记
    Making your C++ code robust
    TGA文件
  • 原文地址:https://www.cnblogs.com/bittorrent/p/2756092.html
Copyright © 2020-2023  润新知