String Format

 
/**
 * STRING FORMATING
 * ----------------
 * String.format() uses printf-style rules.
 * 
 * Formatting is for DISPLAY purposes - formatted values
 * are strings, not numbers.
 * 
 * Basic formatting example:
 *      %6s  -> right-align in a 6-character field (spaces on left)
 *      %-6s -> left-align in a 6-character field (spaces on right)
 */

package com.minte9.basics.strings;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StringFormat {
    public static void main(String[] args) {

        // Right align string, manually prefixed with a "0"
        String a = "0" + String.format("%6s", "123");

        // Right-align string, spaces replaces with zeros
        String b = String.format("%6s", "123").replace(" ", "0");

        // Left-align string, spaces replaces with zeros
        String c = String.format("%-6s", "123").replace(" ", "0");

        System.out.println(a); // 0  123
        System.out.println(b); // 000123
        System.out.println(c); // 123000

        // ---------------------------------------------------------
        
        List<Integer> N = new ArrayList<>();
        List<String> S = new ArrayList<>();
        
        N = Arrays.asList(100, 65, 50);
        S = Arrays.asList("java", "cpp", "python");

        for (int i=0; i<N.size(); i++) {
            System.out.print(

                // %-15s -> left align string, width 15
                String.format("%-15s", S.get(i)) +

                // %03d -> right align integer, width 3, padded with zeros
                String.format("%03d", N.get(i)) + 
                
                "\n"
            );
            // ------------------
            // java          100
            // cpp           065
            // python        050
        }
    }
}

Multilines

 
/**
 * MULTILINES STRINGS
 * ------------------
 * Java (before JDK15) does not permit strings to span lines.
 * 
 * We can span strings on multiple lines using:
 *      - Concatenation operator +
 *      - String.join()
 *      - Text Block """ (only with JDK15)
 */

package com.minte9.basics.strings;

public class Multilines {
    public static void main(String[] args) {
        
        String a = ""
            + "AAA "
            + "BBB"
        ;
        String b = String.join("\n",
            "CCC",
            "DDD"
        );

        System.out.println(a); // AAA BBB
        System.out.println(b); // CCC DDD
    }
}

Converting / Integers

Conveting Strings to Integers and vice versa.
T 
/**
 * Conveting Strings to Integers and vice versa.
 */

package com.minte9.basics.strings;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.Test;

public class StringConvertionTest {

    Integer a = Integer.valueOf("1");  // 1
    Float   b = Float.valueOf("2.22"); // 2.22
    int     x = 11;
    
    @Test public void toNumberTest() {
        assertEquals(a, 1, 0);
        assertNotEquals(a, "1");
        assertEquals(b, 2.23, 0.1);
        assertNotEquals(b, 2.23, 0);
    }

    @Test public void toStringTest() {
        assertEquals("11", "" + x);
        assertEquals("11", "" + String.valueOf(x));
        assertEquals("11", "" + Integer.toString(x));
    }
}

Json

Compare to XML, JSON is much smaller in size.
T 
package com.minte9.basics.strings;
import static org.junit.Assert.assertEquals;

import org.json.JSONObject;
import org.junit.Test;

public class JsonTest {

    @Test public void json() {

        String s = "{message:{type:feed,timestamp:1},error:0}";
        JSONObject obj = new JSONObject(s);

        assertEquals("feed", obj.getJSONObject("message").getString("type"));
            // passed
            
        assertEquals(0, obj.getInt("error"));
            // passed
    }
}

Translate

Custom formats can be easily transtated to Json.
 
/**
 * Translate custom formats to json for easy parsing.
 */

package com.minte9.basics.strings;
import org.json.JSONObject;

public class Translate {
    public static void main(String[] args) {

        //String s = "{message:{type:feed,timestamp:1},error:0}"; // json

        String s = "{message={type=feed|timestamp=1},error=0}"; // not a json
        JSONObject obj;

        s = translate(s);
        obj = new JSONObject(s);

        System.out.println(
            obj.getJSONObject("message").getString("type") // feed
        );

        System.out.println(
            obj.getInt("error") // 0
        );
    }
    
    public static String translate(String s) {

        s = s.replaceAll("([^={}|]+)=", "$1="); // add quotes to keys
        s = s.replaceAll("=([^={}|]+)", "=$1"); // add quotes to values
        s = s.replace("|", ",").replace("=", ":");
            // System.out.println(s);

        return s;
    }
}

Loop

To parse json array, use for-each loop with getJSONArray() method.
 
/**
 * Use getJSONArray() in order to loop an json
 */

package com.minte9.basics.strings;

import org.json.JSONArray;
import org.json.JSONObject;

public class Loop {
    public static void main(String[] args) {

        String str = "{"
            + "orders: ["
                + "{sym:goog,amount:100,error:1},"
                + "{sym:msft,amount:200,error:0}"
            + "], error:0" +
        "}";

        JSONObject obj = new JSONObject(str);
        JSONArray orders = obj.getJSONArray("orders");
            //System.out.println(orders);

        for(Object item : orders) {

            JSONObject order = (JSONObject) item; // Look Here
            System.out.println(""
                + order.getString("sym") 
                + ":"
                + order.getInt("error")
            );
                // goog:1
                // msft:0
        }
    }
}




References: