简体   繁体   English

C:如何将命令行的特殊字符捕获为字符串

[英]C: How to capture special characters of the command line into a string

I would like to capture special characters such as \\n from the command line into a C program. 我想从命令行捕获特殊字符,例如\\ n到C程序中。

For example, for the following program, if I run ./a.out "\\nfoo\\n" , I'd like to to print (newline) foo (newline) instead of "\\nfoo\\n". 例如,对于以下程序,如果我运行./a.out“ \\ nfoo \\ n”,我想打印(newline)foo(newline)而不是“ \\ nfoo \\ n”。 How can I capture that in to a string? 如何捕获到字符串中?

#include <stdio.h>
#include <string.h>

int main(int argc, char ** argv){
    if(argc >1){
        char * s = strdup(argv[1]);
        printf("%s\n", s);
        free(s);
    }
    return 0;
}

Edit: sorry, by (newline) foo (newline), I mean the acutal output is 编辑:对不起,通过(newline)foo(newline),我的意思是实际输出是

foo

Currently,the output is literally "\\nabc\\n".(newlines are not printed because s captures "\\n" 2 characters instead of the '\\n' character). 当前,输出实际上是“ \\ nabc \\ n”。(不打印换行符,因为s捕获“ \\ n”两个字符而不是“ \\ n”字符)。 Sorry about the confusion. 对不起,我很困惑。

make a new string, iterate through the old string adding characters to the new string. 创建一个新字符串,遍历旧字符串,向新字符串中添加字符。 if you ever see the '\\' character, add a special character to the new string based on the next character in the old string. 如果您看到'\\'字符,请根据旧字符串中的下一个字符向新字符串添加一个特殊字符。

C strings cannot grow dynamically, so you will need to allocate space for a new string and fill it with the desired contents. C字符串不能动态增长,因此您将需要为新字符串分配空间,并用所需的内容填充它。 But to know how many characters will be required, you need to make a pass over *s first and count. 但是要知道需要多少个字符,您需要先经过*s并计数。 Once you count the number of characters needed, you can malloc space for a new string, and start iterating over the old string and copying characters. 计算完所需的字符数后,您可以为新字符串malloc空间,然后开始遍历旧字符串并复制字符。 Whenever you encounter one of your "special" characters, copy the appropriate replacement string into the new string. 每当遇到“特殊”字符之一时,将适当的替换字符串复制到新字符串中。

Some code sketches (not tested; if you want to use any of this, you'll have to test and debug yourself): 一些代码草图(未经测试;如果要使用其中任何一个,则必须进行测试和调试):

char* replacement(char c) {
  if(c == '\n')
    return "(newline)";
  else if(c == '\t')
    return "(tab)";
  else
    return NULL;
}

int charactersNeeded(char* s) {
  int count = 0;
  char* r;
  while(*s != '\0') {
    r = replacement(*s);
    if(r != NULL)
      count += strlen(r);
    else
      count++;
    s++;
  }
  return count;
}

void copyString(char* s, char* t) {
  /* it is assumed that t points to a buffer of sufficient length
     to hold all the copied chars, as well as terminating null */
  char* r;
  do {
    r = replacement(*s);
    if(r != NULL) {
      strcpy(t, d);
      t += strlen(d)-1;
    } else *t = *s;
    s++;
    t++;
  } while(*s != '\0');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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