簡體   English   中英

C:如何將命令行的特殊字符捕獲為字符串

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

我想從命令行捕獲特殊字符,例如\\ n到C程序中。

例如,對於以下程序,如果我運行./a.out“ \\ nfoo \\ n”,我想打印(newline)foo(newline)而不是“ \\ nfoo \\ n”。 如何捕獲到字符串中?

#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;
}

編輯:對不起,通過(newline)foo(newline),我的意思是實際輸出是

當前,輸出實際上是“ \\ nabc \\ n”。(不打印換行符,因為s捕獲“ \\ n”兩個字符而不是“ \\ n”字符)。 對不起,我很困惑。

創建一個新字符串,遍歷舊字符串,向新字符串中添加字符。 如果您看到'\\'字符,請根據舊字符串中的下一個字符向新字符串添加一個特殊字符。

C字符串不能動態增長,因此您將需要為新字符串分配空間,並用所需的內容填充它。 但是要知道需要多少個字符,您需要先經過*s並計數。 計算完所需的字符數后,您可以為新字符串malloc空間,然后開始遍歷舊字符串並復制字符。 每當遇到“特殊”字符之一時,將適當的替換字符串復制到新字符串中。

一些代碼草圖(未經測試;如果要使用其中任何一個,則必須進行測試和調試):

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