c++ 複習知識

c++ 複習知識:

輸入字符串,字符 參考鏈接

1、cin>>

用法1:最基本,也是最常用的用法,輸入一個數字:

注意:>> 是會過濾掉不可見字符(如 空格 回車,TAB 等)
cin>>noskipws>>input[j];//不想略過空白字符,那就使用 noskipws 流控制

用法2:接受一個字符串,遇“空格”、“TAB”、“回車”都結束

#include <iostream>
using namespace std;
main ()
{
char a[20];
cin>>a;
cout<<a<<endl;
}

2、cin.get()

用法1: cin.get(字符變量名)可以用來接收字符

用法2:cin.get(字符數組名,接收字符數目)用來接收一行字符串,可以接收空格 字符數目應該包括 ‘\0’;

3、cin.getline() // 接受一個字符串,可以接收空格並輸出

延伸:
cin.getline()實際上有三個參數,cin.getline(接受字符串數組,接受個數包括一個‘\0‘,結束字符)

當第三個參數省略時,系統默認爲’\0’。如果將例子中cin.getline()改爲cin.getline(m,5,‘a’);當輸入jlkjkljkl時輸出jklj,輸入jkaljkljkl時,輸出jk

4. getline(cin,string)
<string> 中:getline:需要include string頭文件

用法:不會忽略space、tab,遇到Enter就結束

string line;
getline(cin,line)
  1. scanf(): EOF = -1
int a, b;
while (scanf("%d %d", &a, &b) != EOF){
    ...
}
  1. getchar(); // take the ‘\n’
  2. 獲取一個字符

c++ 算數計算:

#include <math.h>
//平方 pow()
int a = pow(4,2);// 4的平方=16
//開方
int b = pow(4,0.5);// 4的平方根=2
int c = sqrt(4);// 4的平方根=2
//整數絕對值
int c = abs(b-c);
//浮點數絕對值
double d = fabs(b-c);

c++ String 的用法:參考鏈接

  1. 聲明:

string s;//聲明一個string 對象

string ss[10];//聲明一個string對象的數組

  1. 初始化:
    string s;//默認初始化,一個空字符串
    string s1("ssss");//s1是字面值“ssss”的副本
    string s2(s1);//s2是s1的副本
    string s3=s2;//s3是s2的副本
    string s4(10,'c');//把s4初始化
    string s5="hiya";//拷貝初始化
    string s6=string(10,'c');//拷貝初始化,生成一個初始化好的對象,拷貝給s6

    //string s(cp,n)
    char cs[]="12345";
    string s7(cs,3);//複製字符串cs的前3個字符到s當中

    //string s(s2,pos2)
    string s8="asac";
    string s9(s8,2);//從s2的第二個字符開始拷貝,不能超過s2的size

    //string s(s2,pos2,len2)
    string s10="qweqweqweq";
    string s11(s10,3,4);//s4是s3從下標3開始4個字符的拷貝,超過s3.size出現未定義
  1. substr:
    string s="abcdefg";
//s.substr(pos1,n)返回字符串位置爲pos1後面的n個字符組成的串
    string s2=s.substr(1,5);//bcdef

    //s.substr(pos)//得到一個pos到結尾的串
    string s3=s.substr(4);//efg

4. insert:

  string str="to be question";
    string str2="the ";
    string str3="or not to be";
    string::iterator it;

    //s.insert(pos,str)//在s的pos位置插入str
    str.insert(6,str2);                 // to be the question

    //s.insert(pos,str,a,n)在s的pos位置插入str中插入位置a到後面的n個字符
    str.insert(6,str3,3,4);             // to be not the question

    //s.insert(pos,cstr,n)//在pos位置插入cstr字符串從開始到後面的n個字符
    str.insert(10,"that is cool",8);    // to be not that is the question

    //s.insert(pos,cstr)在s的pos位置插入cstr
    str.insert(10,"to be ");            // to be not to be that is the question

    //s.insert(pos,n,ch)在s.pos位置上面插入n個ch
    str.insert(15,1,':');               // to be not to be: that is the question

    //s.insert(s.it,ch)在s的it指向位置前面插入一個字符ch,返回新插入的位置的迭代器
    it = str.insert(str.begin()+5,','); // to be, not to be: that is the question

    //s.insert(s.it,n,ch)//在s的it所指向位置的前面插入n個ch
    str.insert (str.end(),3,'.');       // to be, not to be: that is the question...

    //s.insert(it,str.ita,str.itb)在it所指向的位置的前面插入[ita,itb)的字符串
    str.insert (it+2,str3.begin(),str3.begin()+3); // to be, or not to be: that is the question...

5. erase操作:
用來執行刪除操作
刪除操作有三種

  1. 指定pos和len,其中pos爲爲起始位置,pos以及後面len-1個字符串都刪除
  2. 迭代器,刪除迭代器指向的字符
  3. 迭代器範圍,刪除這一範圍的字符串,範圍左閉右開
                          // "This is an example sentence."
  str.erase (10,8);       //            ^^^^^^^^
  //直接指定刪除的字符串位置第十個後面的8個字符
  std::cout << str << '\n';
                            // "This is an sentence."
  str.erase (str.begin()+9);//           ^
  //刪除迭代器指向的字符
  std::cout << str << '\n';
                            // "This is a sentence."
                            //       ^^^^^
  str.erase (str.begin()+5, str.end()-9);
  //刪除迭代器範圍的字符
  std::cout << str << '\n';// "This sentence."

6. append和replace操作:

append函數可以用來在字符串的末尾追加字符和字符串。由於string重載了運算符,也可以用+=操作實現

repalce顧名思義,就是替換的意思,先刪除,後增加。

// append:
 std::string str;
    std::string str2="Writing ";
    std::string str3="print 10 and then 5 more";

    //直接追加一個str2的字符串
    str.append(str2);                       // "Writing "
    //後面追加str3第6個字符開始的3個字符串
    str.append(str3,6,3);                   // "10 "
    //追加字符串形參的前5個字符
    str.append("dots are cool",5);          // "dots "
    //直接添加
    str.append("here: ");                   // "here: "
    //添加10個'.'
    str.append(10u,'.');                    // ".........."
    //添加str3迭代器範圍的字符串
    str.append(str3.begin()+8,str3.end());  // " and then 5 more"
    //最後這個比較特殊,意思是添加5個'A',實際上參數裏面的65對應的asc碼就是65
    str.append<int>(5,65);                // "....."
    //字符串追加也可以用重載運算符實現
    str+="lalala";
    std::cout << str << '\n';

replace:

// replace:
    std::string str="this is a test string.";
    std::string str2="n example";
    std::string str3="sample phrase";
    std::string str4="useful.";
//第9個字符以及後面的4個字符被str2代替
    str.replace(9,5,str2);          // "this is an example string." (1)
    //第19個字符串以及後面的5個字符用str的第7個字符以及後面的5個字符代替
    str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
    //第8個字符以及後面的9個字符用字符串參數代替
    str.replace(8,10,"just a");     // "this is just a phrase."     (3)
    //第8個字符以及後面的5個字符用字符串參數的前7個字符替換
    str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
    //第22以及後面的0個字符用3個歎號替換
    str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)
    //迭代器的原理同上
    // Using iterators:                                               0123456789*123456789*
    str.replace(str.begin(),str.end()-3,str3);                    // "sample phrase!!!"      (1)
    str.replace(str.begin(),str.begin()+6,"replace");             // "replace phrase!!!"     (3)
    str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    // "replace is cool!!!"    (4)
    str.replace(str.begin()+12,str.end()-4,4,'o');                // "replace is cooool!!!"  (5)
    str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful."    (6)

7. assign操作:

assign操作在一起列容器當中都存在,比如vector等等。是一個很基本的操作函數,string使用assign可以靈活的對其進行賦值。

    std::string str;
    std::string base="The quick brown fox jumps over a lazy dog.";

    // used in the same order as described above:
    //直接把base賦值給str
    str.assign(base);
    std::cout << str << '\n';
    //把base第10個字符以及後面的8個字符賦給str
    str.assign(base,10,9);
    std::cout << str << '\n';         // "brown fox"
    //把參數中的0到6個字符串賦給str
    str.assign("pangrams are cool",7);
    std::cout << str << '\n';         // "pangram"
    //直接使用參數賦值
    str.assign("c-string");
    std::cout << str << '\n';         // "c-string"
    //給str賦值10個'*'字符
    str.assign(10,'*');
    std::cout << str << '\n';         // "**********"
    //賦值是10個'-'
    str.assign<int>(10,0x2D);
    std::cout << str << '\n';         // "----------"
    //指定base迭代器範圍的字符串
    str.assign(base.begin()+16,base.end()-12);
    std::cout << str << '\n';         // "fox jumps over"
  1. string的搜索操作:

find和rfind函數:

find函數主要是查找一個字符串是否在調用的字符串中出現過,大小寫敏感。

    std::string str ("There are two needles in this haystack with needles.");
    std::string str2 ("needle");

    // different member versions of find in the same order as above:
    //在str當中查找第一個出現的needle,找到則返回出現的位置,否則返回結尾
    std::size_t found = str.find(str2);
    if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';
    //在str當中,從第found+1的位置開始查找參數字符串的前6個字符
    found=str.find("needles are small",found+1,6);
    if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';
    //在str當中查找參數中的字符串
    found=str.find("haystack");
    if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';
    //查找一個字符
    found=str.find('.');
    if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';
    //組合使用,把str2用參數表中的字符串代替
    // let's replace the first needle:
    str.replace(str.find(str2),str2.length(),"preposition");

rfind函數就是找最後一個出現的匹配字符串,返回的位置仍然是從前往後數的。

std::string str ("The sixth sick sheik's sixth sheep's sick.");
    std::string key ("sixth");//                    ^
    //rfind是找最後一個出現的匹配字符串
    std::size_t found = str.rfind(key);
    if (found!=std::string::npos)
    {
        cout<<found<<endl;//輸出23
        str.replace (found,key.length(),"seventh");//找到的sixth替換成seventh
    }

3.find_….of函數:

  1. find_first_of(args) 查找args中任何一個字符第一次出現的位置
  2. find_last_of(args) 最後一個出現的位置
  3. find_fist_not_of(args) 查找第一個不在args中的字符
  4. find_last_not_of 查找最後一個不在args中出現的字符
std::string str1 ("Please, replace the vowels in this sentence by asterisks.");
    std::size_t found1 = str1.find_first_of("aeiou");
    //把所有元音找出來用*代替
    while (found1!=std::string::npos)
    {
        str1[found1]='*';
        found1=str1.find_first_of("aeiou",found1+1);
    }
    std::cout << str1 << '\n';

    //在str2中找到第一個不是消協英文字母和空格的字符
    std::string str2 ("look for non-alphabetic characters...");
    std::size_t found2 = str2.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
    if (found2!=std::string::npos)
    {
        std::cout << "The first non-alphabetic character is " << str2[found2];
        std::cout << " at position " << found2 << '\n';
    }

8. 比較與數值轉化:

如果兩個字符串相等,那麼返回0,調用對象大於參數返回1,小於返回-1。

string重載了運算符,可以直接用>,<,==來進行比較,也很方便

string s1="123",s2="123";
    cout<<s1.compare(s2)<<endl;//0

    s1="123",s2="1234";
    cout<<s1.compare(s2)<<endl;//-1

    s1="1234",s2="123";
    cout<<s1.compare(s2)<<endl;//1

    std::string str1 ("green apple");
    std::string str2 ("red apple");

    if (str1.compare(str2) != 0)
    std::cout << str1 << " is not " << str2 << '\n';
    //str1的第6個字符以及後面的4個字符和參數比較
    if (str1.compare(6,5,"apple") == 0)
    std::cout << "still, " << str1 << " is an apple\n";

    if (str2.compare(str2.size()-5,5,"apple") == 0)
    std::cout << "and " << str2 << " is also an apple\n";
    //str1的第6個字符以及後面的4個字符和str2的第4個字符以及後面的4個字符比較
    if (str1.compare(6,5,str2,4,5) == 0)
    std::cout << "therefore, both are apples\n";

9 .數值轉換:學習鏈接

在io的部分有過數值和字符串相互轉換的例子,使用的是stringstream函數,在c++11當中有定義好的現成的函數取調用,非常方便。

一、int轉string

1.c++11標準增加了全局函數std::to_string:

string to_string (int val);

string to_string (long val);

string to_string (long long val);

string to_string (unsigned val);

string to_string (unsigned long val);

string to_string (unsigned long long val);

string to_string (float val);

string to_string (double val);

string to_string (long double val);

二、string轉int:

 stoi(s,p,b); //int
 stol(s,p,b); // long
 stod() //double
 stof() // float
 stoul(s,p,b);// unsigned long
 stoll(s,p,b);// long l
 stoull(s,p,b); // u l l 

其中b表示轉換所用的基數,默認爲10(表示十進制).

p是size_t的指針,用來保存s中第一個非數值字符的下標,p默認爲0,即函數不返 回下標.

9.返回某一個char:
str.at()

10. 字符長度
str.length()
str.size()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章