c++数组,append,substr的用法

c++动态创建数组的方式:
一维的:
  • int *a=new int[10];
  • vector<int> a{ };
二维的:

int **array;
//array = (int **)malloc(sizeof(int *)*row);//方法一
array=new int *[row];
for(int i=0;i!=row ; i++)
//array[i]=(int *) malloc(sizeof(int )*column);//方法一
array[i]=new int [column];
1.append用法
(1)append函数是向string后面追加字符或字符串
string s="hello ";
const char *c="out here ";
s.append(c);
s="hello out here "
(2) 向string后面添加字符串的一部分
string s="hello ";
const char *c="out here";
s.append(c,3);//把c字符串的前n个字符连接到当前字符串末尾
s="hello out"
(3)向string后面添加string
1 string s1 = "hello "; 
2 string s2 = "wide "; 
3 string s3 = "world ";
4 s1.append(s2);       //把字符串s连接到当前字符串的结尾
5 s1 = "hello wide ";   
6 s1 += s3;
7 s1 = "hello wide world "; 
(4)向string添加string的一部分
1 string s1 = "hello ", s2 = "wide world ";
2 s1.append(s2, 5, 5); //
3 //把字符串s2中从5开始的5个字符连接到当前字符串的结尾
4 s1 = "hello world";
5 string str1 = "hello ", str2 = "wide world ";
6 str1.append(str2.begin()+5, str2.end()); 
7 //把s2的迭代器begin()+5和end()之间的部分连接到当前字符串的结尾
8 str1 = "hello world";
(5)向string后面添加多个字符
1 string s1 = "hello ";
2 s1.append(4,'!'); //在当前字符串结尾添加4个字符!
3 s1 = "hello !!!!";
2、substr
1 string s="abcdefg";
2 string a=s.substr(0,5);
3 a="abcde";//a是从0开始的长度为5的字符串

 

用途:一种构造字符串的方法。
形式:s.substr(pos,n)
解释:返回一个string,包含s中从pos开始的n个字符的拷贝,(pos的默认值是0,n的默认值是s.size()-pos,即不加参数会默认拷贝。
补充:若pos的值超过s的大小,则substr会抛出一个out_of_range异常;若pos+n的值超过s的大小,则substr会调整n的值,只拷贝到string的末尾。

原文链接: https://www.cnblogs.com/jiaxinli/p/13330518.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c++数组,append,substr的用法

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/367914

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 下午6:06
下一篇 2023年3月2日 下午6:07

相关推荐