2011-08-23 18 views
0

如何編輯用雙引號和反斜線這樣一個如何編輯和使用包含雙引號和轉義字符的字符串?

「我愛\」程序\「的字符串」

,並打印這樣

我愛「編程」

我發現這個在線,但沒有運氣:

for (int i = 0; i < lineLength; i++) 
{ 
    if (line[i] == '\\') 
    { 
     line[j++] = line[i++]; 
     line[j++] = line[i]; 
     if (line[i] == '\0') 
      break; 
    } 
    else if (line[i] != '"') 
     line[j++] = line[i]; 
} 
line[j] = '\0'; 
+0

我只是搜索堆棧溢出爲「用C刪除引號」 - 這是#1響應:http://stackoverflow.com/questions/7143878/how-to-remove-quotes-from-a- string-in-c –

+0

@ michael15你能否將你的問題中的代碼變成一個完整的C函數,幷包含一些樣本輸入和期望的輸出?我們需要知道你遇到了什麼問題。 –

+0

爲什麼你需要對它做任何事情?它會按照你想要的方式打印。 – EJP

回答

1

當你遇到反斜槓,你目前正在複製後衛h和下一個字符。實際上你需要做的只是增加反斜槓,然後像下一個字符那樣拷貝下一個字符,而不是反斜槓或者引號。而不是line[j++] = line[i++];(對於您的if正文中的第一行),您只需要i++;

還有其他一些事情可以修復,但應該讓它工作。

0

恕我直言,讀/寫指針方法是處理這些刪除字符問題時最簡單的方法之一,它使得算法易於遵循。

void RemoveQuotes(char * Str) 
{ 
    const char * readPtr=Str; 
    char * writePtr=Str; 
    for(;*readPtr; readPtr++, writePtr++) 
    { 
     /* Checks the current character */ 
     switch(*readPtr) 
     { 
      case '\"': 
       /* if there's another character after this, skip the " */ 
       if(readPtr[1]) 
        readPtr++; 
       /* otherwise jump to the check and thus exit from the loop */ 
       else 
        continue; 
       break; 
      case '\\': 
       /* if a " follows, move readPtr ahead, so to skip the \ and copy 
        the "; otherwise nothing special happens */ 
       if(readPtr[1]=='\"') 
        readPtr++; 
       break; 
     } 
     /* copy the characters */ 
     *writePtr=*readPtr; 
    } 
    /* remember to NUL-terminate the string */ 
    *writePtr=0; 
} 
相關問題