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的末尾。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM