C++:String和字符串数组操作函数

在这里插入图片描述
strstr(str1,str2) :用于判断字符串str2是否是str1的子串。如果是,则该函数返回 str1字符串从 str2第一次出现的位置开始到 str1结尾的字符串;否则,返NULL;

strlen(char const* str):用来计算指定字符串 str 的长度,但不包括结束字符(即 null 字符);

strcat(str,ptr):是将字符串ptr内容连接到字符串str后,然后得到一个组合后的字符串str;

strcpy( char * dst, const char * src ):把字符串src复制到一分配好的字符串空间dst中,复制的时候包括标志字符串结尾的空字符一起复制。操作成功,返回dst,否则返回NULL;

strcmp(str1,str2):比较两个字符串并根据比较结果返回整数;若str1=str2,则返回零;若str1<str2,则返回负数;若str1>str2,则返回正数;

strncpy(char *dest, const char *src, int n):用于将指定长度的字符串复制到字符数组中;把src所指向的字符串中以src地址开始的前n个字节复制到dest所指的数组中,并返回被复制后的dest。

strncmp ( const char * str1, const char * str2, size_t n ):把 str1 和 str2 进行比较,最多比较前 n 个字节,若str1与str2的前n个字符相同,则返回0;若s1大于s2,则返回大于0的值;若s1 小于s2,则返回小于0的值;


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


代码示例:

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;

int main()
{
	cout<<"please input name:"<<endl;

	string name;
	getline(cin,name);//如果直接回车,也会传给name;cin无法做到;

	if(name.empty())//不能用if(name == "\n")
	{
		cout<<"the input is null;"<<endl;
		system("pause");
		return 0;
	}

	if(name == "imooc")
	{
		cout<<"you are an administrators"<<endl;
	}

	cout<<"hello "+name<<endl;
	cout<<"the length of your name is:"<<name.size()<<endl;
	cout<<"the first letter of your name is:"<<name[0]<<endl;

	system("pause");
	return 0;
}

单元巩固:

定义一个Student类,包含名字和年龄两个数据成员,实例化一个Student对象,并打印出其成两个数据成员

#include <iostream>
#include <string>
using namespace std;

/**
  * 定义类:Student
  * 数据成员:名字、年龄
  */
class Student
{
public:
    // 定义数据成员名字 m_strName 和年龄 m_iAge
    string m_strName;
    int m_iAge;
};

int main()
{
    // 实例化一个Student对象stu
    Student stu;
    // 设置对象的数据成员
    stu.m_strName = "慕课网";
    stu.m_iAge = 2;
    
    // 通过cout打印stu对象的数据成员
    cout <<stu.m_strName << " " << stu.m_iAge<< endl;
    return 0;
}
发布了39 篇原创文章 · 获赞 54 · 访问量 2098

猜你喜欢

转载自blog.csdn.net/qq_42745340/article/details/104521159
今日推荐