java笔试代码题

1、设计一个算法,让一个数组的奇数放在偶数的左边。

解题思路:

/**
 * 数组排序功能
 */
public class test {
    public static void main(String[] args) {
        int[] v = { 1,2,5,4,9};
        test t = new test();
        t.swap(v);
          //循环输出输出排序交换的数组  
        for(int i = 0; i < v.length; i++) {  
            System.out.print(v[i]+" ");  
        } 
    }

    //交换两个数字
    public void swap(int[] v) { 
        for(int i = 0,j = 0;i < v.length; i++){   
            //判断是不是奇数
           if(v[i] % 2 != 0) {                      
               int tmp = v[i];  
               v[i] = v[j];  
               v[j] = tmp;  
               j++;
           }  
       }  
    }  
}
2、去除字符串中的指定字符。

解题思路:
以下方法并不能体现算法

public class StringTest {
    public static void main(String[] args) {
        String str = "hello world!";
        char c = 'h';
        StringTest stringTest = new StringTest();
        System.out.println("新字符串为:" + stringTest.delChar1(str, c));
        System.out.println("新字符串为:" + stringTest.delChar2(str, c));
    } 

    //遍历每一个字符,找到该字符进行替换
    public String delChar1(String str,char c) {
        String newStr = "";
        if(!"".equals(str)) {
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) != c) {
                    newStr += str.charAt(i);
                }
            }
        }
        return newStr;
    }

    //利用replace来进行替换:"将指定字符转换为"""
    public String delChar2(String str,String c) {
        String newStr = "";
        if(!"".equals(str)) {
            newStr = str.replace(c, "");
        }
        return newStr;
    }
}
3、字符串倒序输出

解题思路:

/**
 * 字符串倒序排列
 */
public class StringRever{
    public static void main(String[] args) {
        convertStr("helloworld");
        convertStr2("helloworld");
    }

    //StringBuffer的reverse方法实现反转
    private static void convertStr(String string) {
        String str = new StringBuffer(string).reverse().toString();
        System.out.println(str);        
    }

    //遍历字符串每个字符进行倒序输出
    private static void convertStr2(String string) {
        for(int i=string.length()-1;i>=0;i--){
            System.out.print(string.charAt(i));
        }   
    }
}

猜你喜欢

转载自blog.csdn.net/lxw983520/article/details/80029646