字串總結2

2021-07-17 00:23:25 字數 872 閱讀 4162

char* 和 int, float 等的格式化轉換

從字串中提取指定型別數字或子串,這種情形也是非常的常見。大部分的情形都可以用sscanf()

和sprintf()

這兩個函式來實現,如果要求複雜,那麼就用正則庫或自己手寫。乙個例子如下:

#include

#include

#include

int main() {

// 從字串中提取數字

char* p = "192.168.1.1";

int a[4];

sscanf(p, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]);

std::cout << a[0] << ", " << a[1] << ", " << a[2] << ", " << a[3] << "\n";

// 從字串中提取數字,指定的字串

char* p2 = "170 60 alice";

int height, weight;

char name[20];

sscanf(p2, "%d %d %s", &height, &weight, name);

std::cout << name << " height: " << height << " weight: " << weight << "\n";

// 浮點型數字轉字串,並四捨五入保留指定位數小數

double pi = 3.1415;

char str[50];

sprintf(str, "%s %.3f", "pi is:", pi);

std::cout << str << "\n";  // 輸出 3.142

return 0;

字串總結?

其實就是模板彙總好伐 1 字串hash 可以解決一切字串問題。複雜度成迷。include using namespace std define maxn 10000 define read x scanf d x define maxm 1500 define ull unsigned long l...

字串總結

字串輸入輸出 getchar 與putchar include include using namespace std int main 兩種輸入方式 scanf c x 只讀取乙個字元 scanf s x 遇到空格,換行才會停止 cin與scanf s x 的作用大致相同 c char st 10...

字串總結

1 找出回文子串 分析 對於回文子串,最深的印象就是正序和倒序產生的字元相同。其實更深刻的表述方式應該是去除首尾字元後,裡面的依然是個回文子串。這一點也是我沒有想到的。利用動態規劃,相當於乙個遞迴歸納的想法,只要s i 1 j 1 是個回文子串,那麼在s i s j 時,s i j 就是個回文子串。...