字串中指定長度的子字串的提取

2021-05-22 02:02:30 字數 497 閱讀 8344

今天由於工作需要,需要提取字串中的後幾個字元,想起了substr(),strncpy(),但是都不是那麼好用,直接使用不太適合,所以想想有沒有別的方法實現,發現如下方法比較好,所以儲存下來,希望提醒自己!

memset或strnset函式可用來對一段記憶體空間全部設定為某個字元

例如,產生n個空格

char s[20]="";

memset( s, ' ', n);s[n]=0;

strnset( s, ' ', n );s[n]=0;

擷取子串

char s="abcdefghijklmn", char d[20];

左擷取s串n個字元到d

strncpy(d, s, n);d[n]=0;

右擷取s串n個字元到d

strncpy(d, s + strlen(s) - n, n);d[n]=0;

s第i個位置開始擷取n個

strncpy(d, s + i - 1, n);d[n]=0;

擷取指定長度的字串

函式說明 擷取指定長度的字串 utf 8專用 漢字和大寫字母長度算1,其它字元長度算0.5 param string str 原字串 param int len 擷取長度 param string etc 省略字元.return string 擷取後的字串 if function exists re...

按照指定長度切割字串

按照指定長度分割字串 param inputstring 需要切割的源字串 param length 指定的長度 return public static string getdivlines string inputstring,int length if remainder 0 string s...

printf 列印 指定長度 字串

原樣輸出字串 printf s str 2.輸出指定長度的字串,超長時不截斷,不足時右對齊 printf ns str n 為指定長度的10進製數值 3.輸出指定長度的字串,超長時不截斷,不足時左對齊 printf ns str n 為指定長度的10進製數值 4.輸出指定長度的字串,超長時截斷,不足...