1.strlen() 字符串长度函数:求字符串长度
int strlen(const chat *s)
#include<iostream>
#include <string.h>
using namespace std;
void main()
{
char s1[] = "abc mnp";
const char *s2 = "hello!";
char s3[80];
cout << "Input a word: ";
cin >> s3;
cout << "s1:" << strlen(s1) << endl;//空格也算有效字符
cout << "s2:" << strlen(s2) << endl;
cout << "s3:" << strlen(s3) << endl;
cout << strlen("iostream.h");
}
2.strcpy() 字符串复制函数:将一个指定的字符串s2复制到指定的字符数组或者字符指针s1,返回值指向复制后的字符串指针
char *strcpy(char *s1,const char *s2)
char *strncpy(char *s1,const char *s2,int n) //复制前n位
3.strcat() 字符串连接函数:把两个给定的字符串连接成一个字符
char * strcat(char *s1,char *s2)
char * strncat(char *s1,char *s2,int n)
4.strcmp() 字符串比较函数:对两个字符串进行比较,并返回其比较结果,int型数
int strcmp(const char *s1,const char *s2)
int strncmp(const char* s1, const char* s2,int n)
结果:=0 相等
>0 s1>s2
<0 s1<s2
#include <iostream>
#include <string.h>
using namespace std;
void main()
{
int result, n;
char s1[80], s2[80];
cout << "Input string #1: ";
cin >> s1;
cout << "Input string #2: ";
cin >> s2;
cout << "Input a number: ";
cin >> n;
result = strncmp(s1, s2, n);
if (result == 0)
{
cout << s1 << " is equal to " << s2 << endl;
}
else if (result < 0)
{
cout << s1 << " is less than " << s2 << endl;
}
else
{
cout << s1 << " is greater than" << s2 << endl;
}
}
Input string #1: abcedf
Input string #2: abcdef
Input a number: 4
因为abcd中的d小于abce中的e,所以s1大于s2
abcedf is greater than abcdef
Input string #1: mpsxyz
Input string #2: mpsxzy
Input a number: 4
mpsxyz is equal to mpsxzy