StringFormat,常用字符串格式化操作

package com.wesley.framework.commen;

import java.util.Collection;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.xwork.StringUtils;

public class StringFormat {

/**
* 模仿C#格式化字符串
*
* @param str
* @param args
* @return
*/
public static String format(String str, String... args) {
for (int i = 0; i < args.length; i++) {
str = str.replaceFirst("\\{" + i + "\\}", args[i]);
}
return str;
}

/**
* 安全链接字符串
*
* @param strs
* @return
*/
public static String softLink(String... strs) {
StringBuffer sb = new StringBuffer();
for (String s : strs) {
sb.append(StringUtils.isEmpty(s) ? "" : s);
}
return sb.toString();
}

/**
* 安全去首位链接字符串
*
* @param strs
* @return
*/
public static String softTrimLink(String... strs) {
StringBuffer sb = new StringBuffer();
for (String s : strs) {
sb.append(StringUtils.trimToEmpty(s));
}
return sb.toString();
}

/**
* 安全toString
*
* @param str
* @return
*/
public static String toString(Object str) {
if (ObjectUtil.isEmpty(str))
return null;
return str.toString();
}

/**
* 通过","链接List
*
* @param strlist
* @return
*/
public static String formatByComma(Collection<String> strlist) {
if (CollectionUtils.isEmpty(strlist))
return "";
String[] strs = new String[strlist.size()];
strlist.toArray(strs);
return StringFormat.formatByComma(strs);
}

/**
* 将数组轻而易举的转换成用逗号分隔的字符串
*
* @param strs
* @return
*/
public static String formatByComma(String... strs) {
return StringFormat.formatByComma(true, strs);
}

/**
* 将数组轻而易举的转换成用逗号分隔的字符串
*
* @param strs
* @return
*/
public static String formatByComma(boolean filterNull, String... strs) {
if (!filterNull)
ArrayUtils.removeElement(strs, null);
String str = ArrayUtils.toString(strs);
return StringUtils.substring(str, 1, str.length() - 1);
}

/**
* 在数组每个元素前后追加数据
*
* @param array
* @param head
* @param end
* @return
*/
public static String[] formatEcho(String head, String end, String... array) {
if (ObjectUtil.isEmpty(array))
return null;
for (int i = 0; i < array.length; i++) {
if (ObjectUtil.isEmpty(array[i]))
continue;
array[i] = head + array[i] + end;
}
return array;
}

/**
* 把用","分割的字符串,转换成数组
*
* @param str
* @return
*/
public static String[] splitByComma(String str) {
return StringUtils.split(str, ",");
}

public static void main(String[] args) {
String[] stringArray = { "Red", "Orange", "Blue", "Brown", "Red" };
System.out.print(StringFormat.formatByComma(stringArray));
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值