今天在学习编程的时候遇到了一个strchr()的使用技巧,觉得十分惊喜,便在此记录下来,顺便记录一下经常出错的strcat()函数。
stract(s1,s2)函数的主要功能是将字符串s2连接到s1后,并返回s1。特别注意:s1,s2代表的是char型字符数组的首地址,而不接受string型。
错误示范:
string s4 = "aaaa";
string s5 = "aaaa";
cout << strcat(s4, s5) << endl;
//程序出错,提示:不存在从string到char的适当转换函数
正确运用:
#include <iostream>
using namespace std;
int main() {
//strcat()函数的展示
char s1[] = "It comes down to a simle choice...";
char s2[] = "get busying living...";
char s3[] = "or gey busying dying...";
cout << "first:" << endl;
cout << strcat(s1, s2) << endl;
cout << "second " << endl;
cout << strcat(s1, s3) << endl;
system("pause");
return0
}
输出:
接着,先熟悉一下strchr()的使用方法。
strchr()主要是得出字符串s中首次出现c字符的地址,若存在c,则返回c的地址;若无,则返回NULL。
举例说明:参数说明:s1为一个字符串的地址(与上文相同),c为一个待查找字符。
#include <iostream>
using namespace std;
int main() {
//strcat()函数的展示
char s1[] = "It comes down to a simle choice...";
char s2[] = "get busying living...";
char s3[] = "or gey busying dying...";
string s4 = "aaaa";
string s5 = "aaaa";
cout << "first:" << endl;
cout << strcat(s1, s2) << endl;
cout << "second " << endl;
cout << strcat(s1, s3) << endl;
//strchr()函数的展示
char c = 'g';//c为待查找的字符
cout << "third:" << endl;
cout << strchr(s1, c) << endl;//从字符串s1中查找第一次出现c的位置
//strchr()函数得出待查找字符所在的位置
cout << "fourth" << endl;
cout << strchr(s1, 'g')-s1;
while (true)
{
}
return 0;
}
输出:
可见在third输出的是g以后的所有字符串,这是因为strchr(s1, c)返回的是'g'的地址,而cout在接收到这个地址后,一直打印剩余的字符串,直到遇见‘/n’。
上面是strchr的基本用法,下面我将讲述一下其妙用。在fourth的输出则是‘g’在s1中的位置,即‘g’是在s1中的第(34+1)个数,这是因为 strchr(s1, 'g')-s1,即为’g‘的地址减去s1首字母’I‘的地址,而在内存里面,其二者的地址是相对的,所以他们的差也是确定的,即为‘g’在s1中的位置。用这个方法便可快速得知字符在字符串上的位置了。