先来一个有意思的例子。
用strcpy和strlen实现strcat
#include <cstring> #include <iostream> using namespace std; //直接把c1字符串后面的内存空间覆盖, //有影响其他数据的风险 void my_strcat(char c1[], const char c2[]) { strcpy( (c1 + strlen(c1) ), c2); } int main(int argc, char const *argv[]) { char hehe[] = "fuck "; my_strcat(hehe, "you"); cout << hehe; return 0; }
以 从字符串中提取数字 为例?
#include <iostream> #include <cstring> using namespace std; template <typename T> void print(T* p) { int k = 0; for (int i = 0; p[i]; ++i) { cout << p[i]; ++k; if (k % 10) cout << " "; else cout << endl; } } bool isDigit(const char& ch) { return (ch >= '0' && ch<= '9'); } int main(int argc, char const *argv[]) { char c[100] = {0}; int extract[100] = {0}; int num = 0, temp = 0; cin.getline(c, 100); for (unsigned int i = 0; i < strlen(c); ) { if (isDigit(c[i]) ) { while(isDigit(c[i]) ) { temp = temp * 10 + c[i] - '0'; ++i; } extract[num] = temp; ++num; temp = 0; continue; } ++i; } print<int>(extract); return 0; }
以上是比较常规的做法,前一位X10 + 后一位。
以下利用atoi这个库函数(有些编译器没这函数。)
大致做法:记录 数字 和非数字的 分界点,用atoi将其转化。
#include <iostream> #include <cstring> using namespace std; template <typename T> void print(T* p) { int k = 0; for (int i = 0; p[i]; ++i) { cout << p[i]; ++k; if (k % 10) cout << " "; else cout << endl; } } bool isDigit(const char& ch) { return (ch >= '0' && ch<= '9'); } int main(int argc, char const *argv[]) { char c[100] = {0}; int extract[100] = {0}; int num = 0, temp = 0; cin.getline(c, 100); for (unsigned int i = 0; i < strlen(c); ) { if (isDigit(c[i]) ) { while(isDigit(c[i]) ) { temp = temp * 10 + c[i] - '0'; ++i; } extract[num] = temp; ++num; temp = 0; continue; } ++i; } print<int>(extract); return 0; }