Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将两个字符串分成子字符串并配对_Java_String_Dictionary_Substring - Fatal编程技术网

Java 将两个字符串分成子字符串并配对

Java 将两个字符串分成子字符串并配对,java,string,dictionary,substring,Java,String,Dictionary,Substring,我正在为这个问题寻找有趣的解决方案: String key = "1;2;3;4"; String value = "Value1;Value2;Value whitespace;" 现在“;”将每个值与另一个值区分开来。相同的符号“;”把钥匙也分开 现在我想以以下内容结束: {"1" : "Value1", "2" : "Value2", "3" : "Value whitespace", "4" : null} 当然,如果值大于键,则在对的左侧空值应该是no(空值:“Value5”) 我

我正在为这个问题寻找有趣的解决方案:

String key = "1;2;3;4";
String value = "Value1;Value2;Value whitespace;"
现在“;”将每个值与另一个值区分开来。相同的符号“;”把钥匙也分开

现在我想以以下内容结束:

{"1" : "Value1", "2" : "Value2", "3" : "Value whitespace", "4" : null}
当然,如果值大于键,则在对的左侧空值应该是no(空值:“Value5”)

我使用char数组为这个问题提供了一个非常复杂的解决方案,但是对于很多情况和东西来说,这是一个非常复杂的解决方案。所以我很想看到一个正则表达式或子字符串解决方案,或者不包含大循环的东西

编辑: 矿山解决方案:

private List<ExampleObject> getExampleObjects(String key , String value) {
    // s
    if (key  == null || value == null) {
        return new ArrayList<ExampleObject>();
    }

    List<ExampleObject> exampleObjects = new ArrayList<ExampleObject>();

    char[] keyToCharArray = key.toCharArray();
    char[] valueToCharArray = value.toCharArray();

    StringBuilder name = new StringBuilder();
    StringBuilder value = new StringBuilder();

    boolean nameCompleted = false;
    boolean valueCompleted = false;

    for (int i = 0, j = 0; i < keyToCharArray.length || j < valueToCharArray.length;) {
        if (!nameCompleted) {
            char a = ' ';
            try{
                 a = keyToCharArray[i];
            } catch(Exception e){
                 a = ';';
                // throw : VALES and key  not match. More key  then value
                //throw(e);
            }

            if (a == ';' ) {
                nameCompleted = true;
            } else if (!(i + 1 < keyToCharArray.length)){
                name.append(a);
                nameCompleted = true;
            }   else {
                name.append(a);

            }
            i++;
        }
        if (!valueCompleted) {

            char a = ' ';
            try{
                 a = valueToCharArray[j];
            } catch(Exception e){
                 a = ';';
                // throw : VALES and key  not match. More value then key 
                //throw(e);
            }

            if (a == ';') {
                valueCompleted = true;
            } else if(!(j + 1 < valueToCharArray.length)) {
                value.append(a);
                valueCompleted = true;
            } else {
                value.append(a);
            }
            j++;
        }
        if (nameCompleted && valueCompleted) {
            exampleObjects.add(new ExampleObject(name.toString(), value.toString()));
            name.setLength(0);
            value.setLength(0);
            nameCompleted = false;
            valueCompleted = false;
        }
    }
    return exampleObjects;
}
私有列表getExampleObjects(字符串键、字符串值){
//
if(key==null | | value==null){
返回新的ArrayList();
}
List exampleObjects=new ArrayList();
char[]keytocharray=key.tocharray();
char[]valuetocharray=value.tocharray();
StringBuilder名称=新的StringBuilder();
StringBuilder值=新的StringBuilder();
布尔名称完成=假;
布尔值completed=false;
对于(int i=0,j=0;i
其中ExampleObject.class有key和value字段。

请尝试以下操作:(如果要按所述打印字符串)

  • 使用
    String#Split()
  • 值[]
    键[]
  • 创建一个
    布尔值
    ,以指示是否追加了键或值
  • 使用
    StringBuilder
    并循环键的长度[]
  • 附加内容
  • 使用
    StringBuilder\append()
  • 完成了。在查看解决方案之前,请先尝试

    StringBuilder:
    字符串:

    我打印字符串的解决方案:

    public static void main(String[] args) {
        String key = "1;2;3;4";
        String value = "Value1;Value2;Value whitespace";
    
        String[] keys = key.split(";");
        String[] values = value.split(";");
    
        StringBuilder sb = new StringBuilder("{");
        boolean isKey = true;
        int keyCount = 0;
        int valueCount = 0;
    
        for(int i = 0; i < key.length(); i++) {
            sb.append("\"");
    
            if(isKey) {
                sb.append(keys[keyCount]).append("\" : ");
                keyCount++;
            } else {
                sb.append(values[valueCount]).append("\", ");
                valueCount++;
            }
            isKey = !isKey;
        }
    
        sb.append("}");
        System.out.println(sb.toString());
    }
    
    publicstaticvoidmain(字符串[]args){
    字符串key=“1;2;3;4”;
    String value=“Value1;Value2;值空白”;
    String[]keys=key.split(“;”);
    字符串[]值=值。拆分(“;”);
    StringBuilder sb=新的StringBuilder(“{”);
    布尔值isKey=true;
    int keyCount=0;
    int valueCount=0;
    对于(int i=0;i
    我为您的问题想出了一个解决方案:

    输出

    {"1" : "Value1", "2" : "Value2", "3" : "Value whitespace", "4" : "null"}       
    
    代码

    public class HelloWorld{
    
         public static void main(String []args){
            String key = "1;2;3;4";
            String value = "Value1;Value2;Value whitespace;";
    
            String[] keyArr = key.split(";");
            String[] valueArr = value.split(";");
    
            String finalJSON = "{";
            for(int i=0; i<(keyArr.length > valueArr.length ? keyArr.length : valueArr.length); i++) {
    
                try {
                    finalJSON += "\"" + keyArr[i] + "\"";
                }
                catch(ArrayIndexOutOfBoundsException e) {
                    finalJSON += "\"null\"";
                }
    
                finalJSON += " : ";
    
                try {
                    finalJSON += "\"" + valueArr[i] + "\"";
                }
                catch(ArrayIndexOutOfBoundsException e) {
                    finalJSON += "\"null\"";
                }
                if(i!=(keyArr.length > valueArr.length ? keyArr.length : valueArr.length) - 1) 
                    finalJSON += ", ";
            }
            finalJSON += "}";
    
            System.out.println(finalJSON);
         }
    }
    
    公共类HelloWorld{
    公共静态void main(字符串[]args){
    字符串key=“1;2;3;4”;
    String value=“Value1;Value2;值空白;”;
    字符串[]keyArr=key.split(“;”);
    字符串[]valueArr=value.split(“;”);
    字符串finalJSON=“{”;
    对于(int i=0;i valueArr.length?keyArr.length:valueArr.length);i++){
    试一试{
    finalJSON+=“\”“+keyArr[i]+“\”;
    }
    捕获(阵列索引边界外异常e){
    finalJSON+=“\”空\”;
    }
    finalJSON+=“:”;
    试一试{
    finalJSON+=“\”“+valueArr[i]+“\”;
    }
    捕获(阵列索引边界外异常e){
    finalJSON+=“\”空\”;
    }
    如果(i!=(keyArr.length>valueArr.length?keyArr.length:valueArr.length)-1)
    最终JSON+=“,”;
    }
    finalJSON+=“}”;
    System.out.println(finalJSON);
    }
    }
    
    另一种观点:不要“手动”做这些事情

    我的意思是:不要自己做所有的“低级”操作;你应该抽象

    首先,将键值字符串转换为映射

    String keys[] = keyString.split(";");
    String values[] = valueString.split(";);
    
    ... probably some consistency checks that arrays have same length; and  no nulls in keys
    
    Map<String, String> map = new HashMap<>();
    for (int i=0; i < keys.length; i++) {
      map.put(keys[i], values[i]);
    }
    
    stringkeys[]=keyString.split(“;”);
    字符串值[]=valueString.split(“;”);
    ... 可能是对数组长度相同的一致性检查;键中没有空值
    Map Map=newhashmap();
    for(int i=0;i
    最后,使用一些现有的JSON库简单地基于该映射生成JSON表示

    换句话说:除非你谈论的是有数百万条记录的列表;不要担心性能。相反,要担心好的抽象,而不是重新发明w
    String key = "1;2;3;4";
    String value = "Value1;Value2;Value whitespace;";
    String[] keys = key.split(";", -2);
    String[] values = value.split(";", -2);
    
    Map<String, String> result = IntStream.range(0, keys.length).mapToObj(i->i).collect(Collectors.toMap(i->keys[i], i-> values[i]));
    result.entrySet().forEach(e->result.put(e.getKey(), e.getValue().length()==0 ? null : e.getValue()));
    
    /**
     * General pair of items.
     *
     * @param <P> - Type of the first item in the pair.
     * @param <Q> - Type of the second item.
     */
    static class Pair<P, Q> {
        final P p;
        final Q q;
    
        public Pair(P p, Q q) {
            this.p = p;
            this.q = q;
        }
    
        @Override
        public String toString() {
            return "{" + p + "," + q + "}";
        }
    }
    
    /**
     * Gets the `n`th item is present in the array - otherwise returns null.
     *
     * @param a   - The array
     * @param n   - Which one in the array we want.
     * @param <T> - The type of the array entries.
     * @return - The `n`th entry in the array or null if not present.
     */
    private static <T> T n(T[] a, int n) {
        return n < a.length ? a[n] : null;
    }
    
    /**
     * Pairs up each element in the arrays.
     *
     * @param <P> - The type of the elements in the `P` array.
     * @param <Q> - The type of the elements in the `Q` array.
     * @param ps  - The `P` array.
     * @param qs  - The `Q` array.
     * @return A list of `Pair`s of each element.
     */
    static <P, Q> List pairUp(P[] ps, Q[] qs) {
        return IntStream.range(0, Math.max(ps.length, qs.length))
                .mapToObj(i -> new Pair<>(n(ps, i), n(qs, i)))
                .collect(Collectors.toList());
    }
    
    /**
     * Splits the two strings on a separator and returns a list of Pairs of the corresponding items.
     *
     * @param a         - The first string.
     * @param b         - The second string.
     * @param separator - The separator.
     * @return - A List of Paired up entries from `a` and `b`.
     */
    private static List<Pair<String, String>> fold(String a, String b, String separator) {
        return pairUp(a.split(separator, -1), b.split(separator, -1));
    }
    
    public void test() {
        System.out.println(fold("1;2;3;4", "Value1;Value2;Value whitespace", ";"));
    }