當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ basic_string c_str用法及代碼示例


basic_string::c_str()是C++中的內置函數,該函數返回一個指向數組的指針,該數組包含一個空終止的字符序列,這些序列表示basic_string對象的當前值。此數組包含組成basic_string對象值的相同字符序列,最後還有一個額外的終止null-character。

用法:

const CharT* c_str() const

參數:該函數不接受任何參數。


返回值:該函數返回一個以Null結尾的常量指針,該指針指向字符串的字符數組存儲。

下麵是上述函數的實現:

示例1:

// C++ code for illustration of 
// basic_string::c_str function 
#include <bits/stdc++.h> 
#include <string> 
using namespace std; 
  
int main() 
{ 
    // declare a example string 
    string s1 = "GeeksForGeeks"; 
  
    // check if the size of the string is same as the 
    // size of character pointer given by c_str 
    if (s1.size() == strlen(s1.c_str())) { 
        cout << "s1.size is equal to strlen(s1.c_str()) " << endl; 
    } 
    else { 
        cout << "s1.size is not equal to strlen(s1.c_str())" << endl; 
    } 
  
    // print the string 
    printf("%s \n", s1.c_str()); 
}
輸出:
s1.size is equal to strlen(s1.c_str()) 
GeeksForGeeks 

示例2:

// C++ code for illustration of 
// basic_string::c_str function 
#include <bits/stdc++.h> 
#include <string> 
using namespace std; 
  
int main() 
{ 
    // declare a example string 
    string s1 = "Aditya"; 
  
    // print the characters of the string 
    for (int i = 0; i < s1.length(); i++) { 
        cout << "The " << i + 1 << "th character of string " << s1 
             << " is " << s1.c_str()[i] << endl; 
    } 
}
輸出:
The 1th character of string Aditya is A
The 2th character of string Aditya is d
The 3th character of string Aditya is i
The 4th character of string Aditya is t
The 5th character of string Aditya is y
The 6th character of string Aditya is a



相關用法


注:本文由純淨天空篩選整理自AdityaTiwari5大神的英文原創作品 basic_string c_str function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。