2023/11/13 字符串处理函数

文章介绍了C++中的四个字符串处理函数:strlen用于计算字符串长度,strcpy和strncpy用于复制字符串,strcat连接字符串,strcmp和strncmp用于比较字符串。通过实例展示了如何在C++中使用这些函数进行字符串操作。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值