zoukankan      html  css  js  c++  java
  • 关于string与cstring的一些总结

    cstring类:

    memsert

    #include <bits/stdc++.h>
    using namespace std;
    int a[50],b[50];
    int main(){
    	memset(a,0,sizeof(a));//将整个数组赋值为0
    	memset(a,-1,sizeof(a));//将整个数组赋值为-1
        //注意!!只有0和-1才可以用memset赋值,其余的1如memset(a,x,sizeof(a))等用memset赋值数组内均不是x
    	return 0;
    } 
    

    memcpy

    #include <bits/stdc++.h>
    using namespace std;
    int a[50],b[50];
    int main(){
    	a[1]=1;
    	a[2]=2;
    	a[3]=3;
    	b[1]=4;
    	b[2]=5;
        memcpy(a,b,sizeof(b));//把b数组赋值给a数组
    	memcpy(a+1,b+1,8);//把b数组从1开始赋值给a,a也从1开始,8是2个int类型,即a[1]=b[1],a[2]=b[2]
    	for (int i=1;i<=5;++i) printf("%d\n",a[i]);
    	return 0;
    } 
    

    string类

    find

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
    	string st="12345 # $ yyu";
    	printf("%d\n",st.find("123"));//查找123的位置,找不到返回-1
    	return 0;
    }
    

    substr

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
    	string st="12345 # $ yyu";
    	string S=st.substr(1,2);//st从1到2的字符串
    	cout << S << endl;
    	return 0;
    }
    

    insert

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
    	string st="12345 # $ yyu";
    	st.insert(st.begin(),'#');//在头插入'#'
    	cout << st << endl;
    	return 0;
    }
    

    erase

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
    	string st="12345 # $ yyu";
    	st.erase(st.find('#'),'#');//删除#后的所有元素
    	cout << st << "end" << endl;
    	return 0;
    }
    

    replace

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
    	string st="12345 # $ yyu";
    	string ss="223";
    	st=st.replace(st.find("#"),1,"u");//从第一个#位置替换第一个#为u
    	cout << st << endl;
    	return 0;
    }
    
    #include <bits/stdc++.h>
    using namespace std;
    int main(){
    	string st="12345 # $ yyu";
    	string ss="224";
    	st=st.replace(0,2,ss,ss.find("2"),3);
    	//用ss的指定子串(从找到2位置数共3个字符)替换从0到2位置上的line
    	cout << st << endl;
    	return 0;
    }
    
    #include <bits/stdc++.h>
    using namespace std;
    int main(){
    	string st="12345 # $ yyu";
    	string ss="221";
    	st=st.replace(0,2,ss);
    	//用ss替换从指定位置0开始长度为3的字符串
    	cout << st << endl;
    	return 0;
    }
    
  • 相关阅读:
    面向对象设计原则之接口隔离原则
    面向对象设计原则之开闭原则
    [OOD]违反里氏替换原则的解决方案
    错误程序
    error: ‘for’ loop initial declarations are only allowed in C99 mode
    函数模板
    查找
    队列类模板
    栈类模板
    单链表的结点类模板
  • 原文地址:https://www.cnblogs.com/zhouykblog/p/9940416.html
Copyright © 2011-2022 走看看