用指针进行字符数组的遍历:
#include <iostream> using namespace std; int main() { char str1[50] = { 0 },str2[] = "hello"; char *pstr1 = str1, *pstr2 = str2; for (; *pstr2 != '\0';) { *pstr1++ = *pstr2++; // 用指针进行遍历 } cout << str1 << endl; // 用数组首地址进行字符串的输出 }
输入一个字符串,例如:a123x456__17960?302ab5876将其中连续的数字作为一个整数,依次存放到一个数组中a中,例如:123放在a[0]中,456放在a[1]中。统计共有多少个整数,并输出这些整数。
#include <iostream> using namespace std; int times = 0; int cpiece(char *pstr); int main() { char str[] = "a123x456__17960?302ab5876"; char *pstr = str; static int i = 0; int num = 0; for (;;) { if (*pstr != '\0') { if ((*pstr - 48 <= 9)&& (*pstr - 48 >= 0)) { i++; if (i == 1) // 用于仅识别数字段 { num = cpiece(pstr); cout << num << endl; } } else { i = 0; } pstr++; // 别忘了遍历字符串时务必使地址逐渐递增 } else { break; } } } int cpiece(char *pstr) // 形参为数字段的第一个数字的地址,子函数的作用是从数字段的第一个数字向后读取直至该段数字段的最后一个数字 { times++; int num = 0; for (; (*pstr <= 57) && (*pstr >= 48);) { num = num * 10 + (*pstr - 48); pstr++; } return num; }