1. 字符串截取,输入为一个字符串和一个数字,但是如果遇到汉字不能只截取半个汉字。
- package cn.lifx.test;
- public class GetNBitChar
- {
- public static void main(String[] args)
- {
- String str1 = "中abc国人def伟大";
- GetNBitChar test = new GetNBitChar();
- String str2 = test.getStr(str1, 1);
- System.out.println(str2);
- str2 = test.getStr(str1, 4);
- System.out.println(str2);
- str2 = test.getStr(str1, 6);
- System.out.println(str2);
- str2 = test.getStr(str1, 8);
- System.out.println(str2);
- str2 = test.getChineseChars(str1);
- System.out.println(str2);
- }
- //获取前n个字节
- public String getStr(String str, int n)
- {
- String temp = "";
- int count = 0;
- int index = 1;
- while(count < n)
- {
- if(str.substring(index-1, index).getBytes().length == 1)
- {
- count++;
- }
- else
- {
- count = count + 2;
- }
- index++;
- }
- temp = str.substring(0, index-1);
- return temp;
- }
- //获得所有汉字
- public String getChineseChars(String str)
- {
- String temp = "";
- StringBuffer sb = new StringBuffer();
- for(int i=1; i<=str.length(); i++)
- {
- temp = str.substring(i-1, i);
- if(temp.getBytes().length == 2)
- {
- sb.append(temp);
- }
- }
- return sb.toString();
- }
- }
2. 一个数组有2n个整数,其中有n个奇数,n个偶数,要求把奇数放在奇数位置,偶数放在偶数位置。
- package cn.lifx.test;
- public class SortOddAndEvenNum
- {
- public static void main(String[] args)
- {
- int[] arr = {2, 3, 4, 6, 8, 5, 7, 9};
- SortOddAndEvenNum sort = new SortOddAndEvenNum();
- sort.Display(arr, "Before:");
- sort.Sort(arr);
- sort.Display(arr, "After:");
- }
- public void Sort(int[] arr)
- {
- int index1 = 0;
- int index2 = 1;
- int temp = 0;
- int n = arr.length;
- while(index1 < n && index2 < n)
- {
- while(arr[index1] % 2 != 0)
- {
- index1 += 2;
- }
- while(arr[index2] % 2 == 0)
- {
- index2 += 2;
- }
- temp = arr[index1];
- arr[index1] = arr[index2];
- arr[index2] = temp;
- index1 += 2;
- index2 += 2;
- }
- }
- public void Display(int[] arr, String str)
- {
- System.out.println(str);
- for(int i=0; i<arr.length; i++)
- {
- System.out.print(arr[i] + " ");
- }
- System.out.println();
- }
- }