`

Java中字符串操作的工具类

    博客分类:
  • java
阅读更多

        Java编程开发中常涉及到字符串的操作。这里提供了关于String一些操作的包装实现。

        1. 获取指定的前缀和后缀之间的内容,返回一个内容列表

       

	/**
	 * 获取指定前缀和后缀之间的内容,并返回一个内容列表
	 * @param str 操作的目标字符串
	 * @param c1 前缀字符
	 * @param c2 后缀字符
	 * @return 挖出的子串列表
	 */
	public static List<String> dugSubstrings(String str, char c1, char c2) {
		List<String> result = new ArrayList<String>();
		int index1 = -1;
		int index2 = -1;
		while ((index1 = str.indexOf(c1, index2 + 1)) != -1
				&& (index2 = str.indexOf(c2, index1 + 1)) != -1) {
			result.add(str.substring(index1 + 1, index2));
		}
		return result;
	}

	/**
	 * 获取指定前缀和后缀之间的内容,并返回一个内容列表
	 * @param str 操作的目标字符串
	 * @param s1 前缀子串
	 * @param s2 后缀子串
	 * @return 挖出的子串列表
	 */
	public static List<String> dugSubstrings(String str, String s1, String s2) {
		List<String> result = new ArrayList<String>();
		int index1 = -1;
		int index2 = -1;
		while ((index1 = str.indexOf(s1, index2 + 1)) != -1
				&& (index2 = str.indexOf(s2, index1 + 1)) != -1) {
			result.add(str.substring(index1 + s1.length(), index2));
		}
		return result;
	}

         单元测试

       

	@Test
	public void testDugSubstringsWithChar() {
		String str = "arr[0][1][2]";
		System.out.println(StringUtil.dugSubstrings(str, '[', ']'));
		// 输出 [0, 1, 2]
	}

	@Test
	public void testDugSubstringsWithString() {
		String str = "map1['key1']=value1&map2['key2']=value2";
		System.out.println(StringUtil.dugSubstrings(str, "['", "']"));
		// 输出 [key1, key2]
	}

        

        2. 字符串的分隔,支持是否对特定范围内的分隔符进行忽略

    

	/**
	 * 用指定符号将字符串分隔,同时支持忽略指定前缀和后缀之间的分隔符号
	 * @param str 操作的目标字符串
	 * @param gap 分隔符
	 * @param exclude1 前缀
	 * @param exclude2 后缀
	 * @return 切分后的子串数组
	 */
	public static String[] splitStringByGap(String str, char gap,
			String exclude1, String exclude2) {
		List<String> strs = new ArrayList<String>();
		int j = -1;
		int i = j;
		j = str.indexOf(gap, i + 1);
		while (j != -1) {
			int t = 0;
			if (str.indexOf(exclude1) < j && (t = str.indexOf(exclude2, j)) > j) {
				j = str.indexOf(gap, t);
			}
			if (j != -1) {
				strs.add(str.substring(i + 1, j));
				i = j;
				j = str.indexOf(gap, i + 1);
			}
		}
		if (i != -1) {
			strs.add(str.substring(i + 1));
		}
		return strs.toArray(new String[1]);
	}

         单元测试

   

	@Test
	public void testSplitStringByGap() {
		String str = "aa.[[bb.cc]].dd";
		List<String> list = Arrays.asList(StringUtil.splitStringByGap(str, '.', "[[", "]]"));
		assertEquals(3, list.size());
		System.out.println(list);
	}

        

        3. 字符串去除所有空白和换行

   

	/**
	 * 将字符串中的转义符去掉
	 * @param str 操作的目标字符串
	 * @return 瘦身后的字符串
	 */
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

         单元测试

   

	@Test
	public void testReplaceBlank() {
		String str = "asdsa\n\tasdsa     \nsadsa\tsadsa\nsadsa";
		System.out.println(str);
		System.out.println(StringUtil.replaceBlank(str));
	}

 

        4. 通过反射将字符串转成基本数据类型

            用于在事先不知道最终需要转换为什么类型的情况下,在通过反射编写工具类时可以用到。

   

	@SuppressWarnings("unchecked")
	/**
	 * 通过反射将字符串转换为基本数据类型
	 * @param str 需要转换的字符串
	 * @param clz 转换后的类型
	 * @return 转换后的值
	 * @throws Exception
	 */
	public static <T> T transferString2PrimitiveType(String str, Class<T> clz)
			throws Exception {
		T obj = null;
		try {
			if (Boolean.class == clz || boolean.class == clz) {
				obj = (T) Boolean.valueOf(str);
			} else if (Character.class == clz || char.class == clz) {
				obj = (T) (Character) str.toCharArray()[0];
			} else if (Short.class == clz || short.class == clz) {
				obj = (T) Short.valueOf(str);
			} else if (Integer.class == clz || int.class == clz) {
				obj = (T) Integer.valueOf(str);
			} else if (Byte.class == clz || byte.class == clz) {
				obj = (T) Byte.valueOf(str);
			} else if (Long.class == clz || long.class == clz) {
				obj = (T) Long.valueOf(str);
			} else if (Double.class == clz || double.class == clz) {
				obj = (T) Double.valueOf(str);
			} else if (Float.class == clz || float.class == clz) {
				obj = (T) Float.valueOf(str);
			}
		} catch (Exception e) {
			throw new Exception(str + "无法转换为" + clz.getSimpleName() + "类型");
		}
		return obj;
	}

         单元测试

   

	@Test
	public void testTransferString2PrimitiveType() throws Exception{
		String str = "true";
		System.out.println(StringUtil.transferString2PrimitiveType(str, Boolean.class));
		str = "12.3f";
		System.out.println(StringUtil.transferString2PrimitiveType(str, Float.class));
		str = "123.44";
		System.out.println(StringUtil.transferString2PrimitiveType(str, Double.class));
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics