summaryrefslogtreecommitdiffstats
path: root/3
diff options
context:
space:
mode:
authorSadeep Madurange <smadurange@users.noreply.github.com>2021-12-02 18:32:18 +0800
committerSadeep Madurange <smadurange@users.noreply.github.com>2021-12-02 18:32:18 +0800
commit401e5d024f88f0787d7f7f99f1d65ee91018107c (patch)
treee8fbcbc8f996d56e59ced7b41b17944c7edc8627 /3
parenta1c867d3eb55dc5ead5b8e2c069746b9785bb7b3 (diff)
downloadk&r-exercises-401e5d024f88f0787d7f7f99f1d65ee91018107c.tar.gz
3.2
Diffstat (limited to '3')
-rw-r--r--3/2.c91
1 files changed, 91 insertions, 0 deletions
diff --git a/3/2.c b/3/2.c
new file mode 100644
index 0000000..f6f6987
--- /dev/null
+++ b/3/2.c
@@ -0,0 +1,91 @@
+#include <stdio.h>
+#include <string.h>
+
+#define ESCAPE 0
+#define UNESCAPE 1
+#define MAXLEN 1000
+
+/* convert new line and tab chars to visible chars */
+void escape(char s[], char t[]);
+
+/* converts escapes sequences to chars */
+void unescape(char s[], char t[]);
+
+int main(int argc, char *argv[]) {
+ int c, i, cmd;
+ char s[MAXLEN], t[MAXLEN];
+
+ if (!strcmp(argv[1], "e"))
+ cmd = ESCAPE;
+ else if (!strcmp(argv[1], "u"))
+ cmd = UNESCAPE;
+ else
+ return 1;
+
+ printf("Enter string to %s and press Ctrl+D\n",
+ cmd == ESCAPE ? "escape" : "unescape");
+
+ for (i = 0; i < MAXLEN - 1 && (c = getchar()) != EOF; i++)
+ t[i] = c;
+ t[i] = 0;
+
+ if (cmd == ESCAPE) {
+ escape(s, t);
+ printf("Escaped output:\n");
+ printf("%s\n", s);
+ } else if (cmd == UNESCAPE) {
+ unescape(s, t);
+ printf("Unescaped output:\n");
+ printf("%s\n", s);
+ } else {
+ return 1;
+ }
+
+ return 0;
+}
+
+void escape(char s[], char t[]) {
+ int c, i, j;
+
+ for (i = 0, j = 0; (c = t[i]) != 0; i++) {
+ switch (c) {
+ case '\n': {
+ s[j++] = '\\';
+ s[j++] = 'n';
+ break;
+ }
+ case '\t': {
+ s[j++] = '\\';
+ s[j++] = 't';
+ break;
+ }
+ default:
+ s[j++] = c;
+ }
+
+ s[j] = 0;
+ }
+}
+
+void unescape(char s[], char t[]) {
+ int c, i, j;
+
+ for (i = 0, j = 0; (c = t[i]) != 0; i++) {
+ if (j > 0 && s[j - 1] == '\\') {
+ switch (c) {
+ case 'n':
+ s[j - 1] = '\n';
+ break;
+ case 't':
+ s[j - 1] = '\t';
+ break;
+ default:
+ s[j++] = c;
+ }
+ } else {
+ s[j++] = c;
+ }
+ }
+
+ s[j] = 0;
+} \ No newline at end of file