查看完整版本: 求了解string的高手
頁: [1]

b2581167 發表於 2018-10-12 08:12 PM

求了解string的高手

想請問各位大大,
如果我要使用strXXX類的API,
例如字串複製、字串合併等...
假如我的字串是string型態的,
我非得要把他轉成char *才行嗎?
能不能不用轉型也能使用的方法??
<div></div>

sggleeee 發表於 2018-10-13 09:48 PM

由您敘述提及的是想直接用string來進行複製,比較,合併等動作....
雖然不知道為何您想用strcpy之類的function....
這裡還是還是提供一個簡單的string操作範例(非使用strXXX function)給您參考,看能不能符合您的需求....
#include <iostream>
#include <string>

using namespace std;

void main()
{
        string s1, s2, s3;
        s1 = "Hi, there ! ";
        s2 = "How's life been treating you?";

        s3 = s1;
       
        cout<<"compare s3 and s1: "<<s3.compare(s1)<<endl;
        cout<<"compare s3 and s2: "<<s3.compare(s2)<<endl;

        s3 = "Hi, There !";
        cout<<"compare s3 and s1: "<<s3.compare(s1)<<endl;

        s3=s1+s2;
        cout<<s3<<endl;
       
        s3.assign(s1,0,2);
        s3.append(s2,5,5);
        cout<<s3<<endl;

        system("pause");       
}
...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div>

z1090128 發表於 2018-10-27 01:50 PM

string不能用str的語法嗎?
因為在映像中好像有使用過類似的

affkame 發表於 2018-10-27 10:45 PM

我覺得提問時, 若可以直接說明目的, 會許版上強者會給你一些更簡單的做法

charleshwu 發表於 2018-10-27 11:34 PM

strxxx 系列的 API 是用來操作 C 語言的字串的,而 string 是 C++ 裡面的 class,它們是不同世界的東西
當然你可以用 string 裡面的 c_str() 來取出 string 裡面的字串指標來使用某些 strxxx  函數,但你最好要弄清楚一切再來這麼做<br><br><br><br><br><div></div>

mountainboy 發表於 2018-11-17 09:53 PM

可以用c_str()將字串取出再處理!

std::string s = "Hello, world";
char* c = new char;
strcpy(c, s.c_str());
頁: [1]