• 反转字符串


    //-----------------------
    String a = "abcde";
    char[] b = a.toCharArray();
    char temp;
    for(int i=0;i<b.length/2;i++) {
        temp = b[i];
        b[i] = b[b.length-i-1];
        b[b.length-i-1] = temp;
    }
    a = new String(b);
    System.out.print(a);
    
    //----------
    String str = "abcd "; 
    String result = new StringBuffer(str).reverse().toString();
    
    
    //-----------------------
    String str = "chentao";
    System.out.print("逆转后的字符串是:[");
    for(int i=str.length()-1;i>=0;i--) {
        char chr = str.charAt(i);
        System.out.print (chr);
    }     
    System.out.print("]");

    String是线程安全的吗?网上搜到的内容仅仅告诉你StringBuffer是线程安全的,而StringBuilder(插入删除用的多,看看API就知道了)不是。那为什么不说String呢,因为没啥好说的,人家是final的千年不变,就是不会改变的,那自然没有同步问题了。记住士兵哥说的就行了,String是不可变序列,拼接和删除都是拷贝到了新内存,而StringBuffer是维护了个缓冲区……

    看下面例子:

    class Go{
        public static void main(String args[]){
            String str1 = "abc";
            String str2 = str1;
            str1 += "de";
            System.out.println(str2);
            
            StringBuffer sb1 = new StringBuffer();
            sb1.append("abc");
            StringBuffer sb2 = sb1;
            sb1.append("de");
            System.out.println(sb2);
        }
    }

    System.out.println(str2)输出的是abc。

    System.out.println(sb2)输出的是abcde。

    不解释……

  • 相关阅读:
    [JSOI2007][BZOJ1031] 字符加密Cipher|后缀数组
    leetcode Flatten Binary Tree to Linked List
    leetcode Pascal's Triangle
    leetcode Triangle
    leetcode Valid Palindrome
    leetcode Word Ladder
    leetcode Longest Consecutive Sequence
    leetcode Sum Root to Leaf Numbers
    leetcode Clone Graph
    leetcode Evaluate Reverse Polish Notation
  • 原文地址:https://www.cnblogs.com/hxsyl/p/3209560.html
Copyright © 2020-2023  润新知