1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class CommandLineEncoder {
  4. public static String encode(Map<String, String> options) {
  5. StringBuilder encodedString = new StringBuilder();
  6. for (Map.Entry<String, String> entry : options.entrySet()) {
  7. String key = entry.getKey();
  8. String value = entry.getValue();
  9. // Encode key and value by escaping special characters
  10. String encodedKey = escapeString(key);
  11. String encodedValue = escapeString(value);
  12. // Append encoded key-value pair to the encoded string
  13. encodedString.append(encodedKey).append("=").append(encodedValue).append(";");
  14. }
  15. // Remove the trailing semicolon
  16. if (encodedString.length() > 0) {
  17. encodedString.deleteCharAt(encodedString.length() - 1);
  18. }
  19. return encodedString.toString();
  20. }
  21. private static String escapeString(String str) {
  22. if (str == null) {
  23. return "";
  24. }
  25. return str.replace("\"", "\\\""); // Escape double quotes
  26. }
  27. public static void main(String[] args) {
  28. // Example usage
  29. Map<String, String> commandLineOptions = new HashMap<>();
  30. commandLineOptions.put("name", "John \"Doe\"");
  31. commandLineOptions.put("age", "30");
  32. commandLineOptions.put("city", "New York");
  33. String encodedOutput = encode(commandLineOptions);
  34. System.out.println(encodedOutput);
  35. }
  36. }

Add your comment