字符串操作
字符串比较
1 2
| boolean result = str1.equals(str2); boolean result = str1.equalsIgnoreCase(str2);
|
搜索与检索
1 2 3 4 5 6 7
| int result = str1.indexOf(str2); int result = str1.indexOf(str2, index); String index = str1.substring(index1); String index = str1.substring(index1, index2);
|
字符串反转
1 2
| StringBuilder sb = new StringBuilder(string); String str = sb.reverse().toString();
|
按单词的字符串反转
1 2 3 4 5 6 7 8 9 10 11
| String str = "hello world"; Deque<String> stack = new ArrayDeque(); StringTokenizer strTok = new StringTokenizer(str); while(strTok.hasMoreTokens()){ stack.push(strTok.nextElement()); } StringBuilder sb = new StringBuilder(); while(!stack.empty()) { sb.append(stack.pop()); sb.append(" "); }
|
大小写转化
1 2
| String strUpper = str1.toUpperCase(); String strLower = str1.toLowerCase();
|
首尾空格移除
1 2
| String str1 = " asdfsdf "; str1.trim();
|
空格移除
字符串转化为数组
1 2
| String str = "tim,kerry,timmy,camden"; String[] results = str.split(",");
|
数据结构
重置数组大小
1 2 3 4 5
| int[] myArray = new int[10]; int[] tmp = new int[myArray.length + 10]; System.arraycopy(myArray, 0, tmp, 0, myArray.length); myArray = tmp;
|
Map 遍历
1 2 3 4 5
| for (Iterator it = map.entrySet().iterator();it.hasNext();){ Map.Entry entry = (Map.Entry)it.next(); Object key = entry.getKey(); Object value = entry.getValue(); }
|
映射集合
1 2 3 4 5 6 7
| HashMap<Type> map = new HashMap<>(); map.put(key, value); map.containsKey(key); map.containsValue(value); Object[] objects = hashmap.entrySet().toArray();
|
数组和列表
1 2 3 4 5 6 7 8
| int[] nums = {1,4,7,324,0,-4}; Arrays.sort(nums); int index = Arrays.binarySearch(nums, number); Collections.sort(List) Object[] objects = arrayList.toArray();
|
Set
- TreeSet排序默认是升序,想要实现自定义排序可以通过传进去一个Comparator或者TreeSet的添加对象实现Comparator接口
遍历
基本数据结构
比较 Double
1 2 3
| Double a = 4.5; Double b = 4.5; boolean result = a.equals(b);
|
二进制、八进制、十六进制转换
1 2 3 4
| int val = 25; String binaryStr = Integer.toBinaryString(val); String octalStr = Integer.toOctalString(val); String hexStr = Integer.toHexString(val);
|
随机数生成
1 2 3 4
| double rn = Math.random(); double value = Math.sqrt(var)*random.nextGaussian()+mean
|
格式化数字
1 2 3 4
| double value = 2343.8798; NumberFormat numberFormatter = NumberFormat.getNumberInstance(); String formattedValue = numberFormatter.format(value); System.out.format("%s%n",formattedValue);
|