【c++语言基础】字符串数组与字符串

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
int main()
{
//字符串复制函数strcpy
char str1[10],str2[]="computer";
strcpy(str1,str2);//复制str2到str1 
puts(str2); 
//字符串数组复制函数strncpy
//意思是将s2指向的字符串的前n个长度的字符放到s1指向的字符串中
//并将s1原有的前n个字符覆盖.
char str3[]="admin",str4[]="computer";
strncpy(str3,str4,4);//复制str4的前4个字符到str3
puts(str3);
//字符串数组连接函数strcat
char str5[]="user-",str6[]="password";
puts(strcat(str5,str6));//将str6连接到str5的后面
//字符串数组链接函数strncat
char str7[]="ABC",str8[]="1234";
puts(strncat(str7,str8,2));//将str8的前n个字符连接到str7的后面
//字符串数组比较函数strcmp
char str9[]="123",str10[]="123";
if(strcmp(str9,str10)==0) cout<<"yes"<<endl;//>,<,=字符串比较ASCII码
//计算字符串长度函数strlen
int n=strlen("language");
cout<<n<<endl; 
char str[20]="Visual Basic";
n=strlen(str);
cout<<n<<endl;
//字符串转换成数值函数
int f=atoi("123.456"); //atoi是int型  atof是double float型  itoa是把int编程string类型 
cout<<f<<endl;
//字符串和字符串数组的相互转换 
string s="Java"; 
char s1[]="abcd"; 
s.copy(s1,4,0);//把s1中从0开始的4个字符复制到s1字符数组
puts(s1); 
puts(s.c_str());//把string转换成c风格字符串,返回的是char指针 
//string允许使用字符数组的函数运算 
//字符串连接可以直接用+和复合赋值+=运算符来实现 
//字符串可以直接使用>,<,=运算符进行比较
//其他常用操作
string t="abcdefghijk";
//获取字符串的长度 
int n1=t.size(); cout<<n1<<endl;
int n2=t.length();cout<<n2<<endl;
//判断是否是空字符串 
bool b=t.empty(); cout<<b<<endl;
//得到子字符串substr 从下标2开始的4个字符 
string t1=t.substr(2,4); cout<<t1<<endl;
//查找子字符串
int n3=t.find("def",0);//从0开始查找def在t中的位置
cout<<n3<<endl;
//删除字符
t.erase(3,5);//从下标3往后删除5个字符
cout<<t<<endl;
//增加字符
t.append("12345",1,3);//在t的末尾增加12345字符从下标1开始的3个字符
cout<<t<<endl;
//字符串的替换和插入操作
t.replace(0,4,t1,2,3);//从0开始删除4个字符,然后再0处插入字符串t1的从2开始的3个字符
cout<<t<<endl; 
}

今天学习了字符串数组和字符串

首先说一个头文件的问题,在c++中就用<cstring>,在c中的话就用<string.h>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值