简体   繁体   中英

how can i revise java String format?

  1. i want to surround with single-quotes if result is null . result=''
  2. and in different case, if result is not empty, surround with single-quotes. like this. result = 'data'

but i thought, this code has problem.

List<ApprovalPath> approvalPaths = new ApprovalPaths(params);

String noticeUsers = String.format("(%s)",StringUtils.toString(getNoticeUsers(approvalPaths),",","'%s'"));

i think that this format will be changed ('%s') but result (null case) = '' and result (not null) = 'data'

i want only single-quotes in two cases(null case/ not null case) but i guess 'not null case' has double single-quotes..

public class StringUtils {

    public static <T> String toString(List<T> list, String seperator) {
        return toString(list,seperator,null);


    }

    public static <T> String toString(List<T> list, String seperator, String format) {

        String result = "";

        for(T item : list) {
            String itemString = item.toString();
            if(format!=null)
                itemString = String.format(format, itemString);
            result += itemString;  
            System.out.println("return : " + result);
        }
        return result;
    }

}

how can i revise this problem?

i have to revise only this code.

String noticeUsers = String format("(%s)",StringUtils.toString(getNoticeUsers(approvalPaths),",","'%s'"));

This would give you the expected outcome:

StringUtils.defaultIfEmpty(StringUtils.wrap("string", "'"), "\"");

public static String wrap(String str, String wrapWith) Wraps a String with another String.

A null input String returns null.

 StringUtils.wrap(null, *) = null StringUtils.wrap("", *) = "" StringUtils.wrap("ab", null) = "ab" StringUtils.wrap("ab", "x") = "xabx" StringUtils.wrap("ab", "\\"") = "\\"ab\\"" StringUtils.wrap("\\"ab\\"", "\\"") = "\\"\\"ab\\"\\"" StringUtils.wrap("ab", "'") = "'ab'" StringUtils.wrap("'abcd'", "'") = "''abcd''" StringUtils.wrap("\\"abcd\\"", "'") = "'\\"abcd\\"'" StringUtils.wrap("'abcd'", "\\"") = "\\"'abcd'\\""

Parameters: str - the String to be wrapper, may be null wrapWith - the String that will wrap str Returns: wrapped String, null if null String input Since: 3.4

StringUtils.wrap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM