在 C string 中的用法

2021-04-13 05:55:37 字數 1840 閱讀 8467

1。 c# 中 字串常量可以以 @ 開頭聲名,這樣的優點是轉義序列「不」被處理,按「原樣」輸出,

即我們不需要對轉義字元加上 / (反斜扛),就可以輕鬆coding。如

string filepath = @"c:/docs/source/a.txt"; // rather than "c://docs//source//a.txt"

2。如要在乙個用 @ 引起來的字串中包括乙個雙引號,就需要使用兩對雙引號了。

這時候你不能使用 / 來轉義爽引號了,因為在這裡 / 的轉義用途已經被 @  「遮蔽」掉了。如

@"""ahoy!"" cried the captain."; // 輸出為: "ahoy!" cried the captain.

有點像sql中的單引號常量處理方式:

declare @msg varchar(100)

set @msg = ''ahoy!'' cried the captain.' -- 輸出為: 'ahoy!' cried the captain.

3。@ 會識別換行符

其實這個特性,我不知道怎麼描述,只是偶然發現的,先看下面的**吧:

string script = @"

";在cs檔案中寫js,結構就很清晰了,正常情況我們是這樣coding的:

string script2 = "";

// or

string script3 =

"";通常我們會選擇後者,因為js**一般比較長,或者方法體很大,或者需要連線其他變數,這樣結構比較清晰。

注意:如果「拼接」的次數很多,應該考慮使用stringbuilder了,有助於提高效能。

還有一種場景,也很常見,在程式中拼接 sql 語句,如

private const string sql_ins_user = @"

insert into t_user([username], [password], email)

values(@username, @password, @email)";

然而,我們需要關注乙個問題:字串長度

看下面的測試**:

private const string sql_ins_user1 = @"

insert into t_user([username], [password], email)

values(@username, @password, @email)";

private const string sql_ins_user2 = @"insert into t_user([username], [password], email)

values(@username, @password, @email)";

private const string sql_ins_user3 = @"insert into t_user([username], [password], email)

values(@username, @password, @email)";

static void main(string args)

可以看到三個字串長度分別相差了,14=126-112和26=112-86,在**編輯器中,sql_ins_user1

中第乙個換行符號之後,縮排13個空格(insert之前),而

sql_ins_user2 中第乙個換行符號之後,縮排25個空格(values之前),

那麼,加上乙個換行符,剛剛好 14和26

如此編寫**,雖然提高了**的清晰度和簡便性,卻無行中帶來了另乙個問題:字元長度!

很多場景下我們希望字串越短越好,如,通過ado.net 傳送 sql 語句給資料庫執行。

所以還是慎用之! 

C String中的find用法

includestring 是c 中乙個非常重要函式。在處理字串的時候經常用到。find是string中乙個查詢函式。示例 上 include includeusing namespace std int main st1.find a 1 後面的數字代表從什麼位置開始查詢。如果不加,預設從位置0 ...

C string中的insert 函式用法詳解

在原串下標為pos的字元前插入字串str basic string insert size type pos,const basic string str str從下標為pos1開始數的n個字元插在原串下標為pos的字元前 basic string insert size type pos,cons...

CString用法集錦

1.cstring compare int compare lpctstr lpsz const 返回值 字串一樣 返回0 小於lpsz 返回 1 大於lpsz 返回1 區分大小字元 cstring s1 abc cstring s2 abd assert s1.compare s2 1 asser...