2010-10-07 33 views
0

C中的轉義序列是什麼?換句話說,我怎麼能問一個while語句來搜索「「「C中的轉義序列?

+0

爲了澄清:給定一個'字符*'你想停下來,當你發現一個雙引號? – 2010-10-07 03:49:45

回答

11

在一個字符常量,你不需要逃避"字符的次數;你可以簡單地使用'"'

在一個字符串,你需要躲避"字符,因爲它是分隔符,你這樣做是通過用一個反斜槓("\"")前綴它

注意,您可以逃脫字符常量的"字符(。 '\"');這是沒有必要的

+0

你也可以用'\ x22'代替'\「'在字符串中搜索雙引號 – Zabba 2010-10-07 03:59:23

+0

@Zabba:如果我在代碼審查中看到'\ x22',我幾乎肯定會考慮它[一個主要代碼WTF](http://28.media.tumblr.com/tumblr_kpu8502s7I1qa3ti5o1_400.jpg)。 – 2010-10-07 04:02:34

+6

當然 - 你應該把它寫成\ 042 – 2010-10-07 04:15:37

1

想要查找的"\""

0

該字符'"',ASCII碼爲34. "In a string literal you escape it like \" this"

1

使用strchr()string.h

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

int main() 
{ 
     char str[] = "This is a sample string with \" another \""; 
     char * pch; 
     printf ("Looking for the '\"' character in: %s ...\n",str); 
     pch=strchr(str,'"'); 
     while (pch!=NULL) 
     { 
      printf ("found at %d\n",pch-str+1); 
      pch=strchr(pch+1,'\"'); 
     } 
     return 0; 
} 
+1

你真的不需要爲此使用string.h。 while(* pch ++!='''&& * pch);'將'pch'移動到雙引號的第一個位置或直到字符串結尾。 – 2010-10-07 03:56:16

+2

但是由於能夠一次搜索整個單詞(或整個16個字節的塊,使用sse等),'strchr'可能會比大字符串快幾倍。 – 2010-10-07 04:05:23

+0

另一方面,如果找不到字符,'strchr'會丟失關於字符串長度的信息,所以如果需要它,您必須浪費'O(n)'調用'strlen'來再次找到它。另一種選擇是'strcspn',但它可能不會針對單個字符集的情況進行優化。 – 2010-10-07 04:07:10