字串與字元陣列
洪翠憶
⚝
⚝
⸎
⚘ ⚘
༻
#include <iostream>
#include <string>
//string型態與其方法是在C++裡的string函式庫
int main(){
std::string s1 = "哈囉天天~";
char s2[] = "你比較常用字串還是字元陣列呢?";
char s3[] = {'h', 'e', 'h', 'e'};
char s4[] = "hehe";
std::cout << s1 << '\n' << s2 << '\n';
std::cout << "s3: " << sizeof(s3) << '\n';
std::cout << "s4: " << sizeof(s4) << '\n';
//字串("")裡結尾處有代表結束符號的\0字元
return 0;
}
/*
哈囉天天~
你比較常用字串還是字元陣列呢?
s3: 4
s4: 5
*/
⸎
⚘ ⚘
༻
#include <iostream>
#include <string>
int main(){
std::string s1 = "meow";
std::cout << s1 << '\n';
s1[0] = 'n';
std::cout << s1 << '\n';
return 0;
}
༻
#include <iostream>
#include <string>
int main(){
std::string s1 = "meow";
s1 = "卍乂" + s1 + "乂卍";
std::cout << s1 << '\n';
return 0;
}
༻
#include <iostream>
#include <string>
int main(){
std::string s1 = "meow";
std::cout << s1[0] << '\n';
std::cout << s1[1:3] << '\n';
return 0;
}
༻
#include <iostream>
#include <string>
int main(){
std::string s1[4] = {"meow", "eowm", "owme", "wmeo"};
std::cout << s1[0] << '\n';
std::cout << s1[1][0] << '\n';
return 0;
}
⸎
⚘ ⚘
༻
#include <string>
...
std::string 名稱;
std::string 名稱 = 值;
std::cout << 字串[索引值];
字串[索引值] = 新的值;
༻
#include <iostream>
#include <string>
int main(){
std::string s;
std::cout << s.empty() << ' ';
s = "hi";
std::cout << s.size() << ' ';
std::cout << s.empty() << ' ';
return 0;
}
//1 2 0
༻
#include <iostream>
#include <string>
int main(){
std::string s = "hi";
std::cout << s << ' ';
s.insert(1, "eee");
//字串.insert(插入索引, 插入字串)
std::cout << s << ' ';
s.erase(s.begin()+1, s.end());
//字串.erase(迭代起始, 迭代終點)
std::cout << s << ' ';
return 0;
}
//hi heeei h
༻
#include <iostream>
#include <string>
int main(){
std::string a, i;
std::cin >> a >> i;
int del = a.find(i), il = i.size();
while(del >= 0 && del < a.size()){
a.erase(a.begin() + del, a.begin() + del + il);
del = a.find(i);
}
std::cout << a << '\n';
return 0;
}
༻
字串.c_str()
語法
⸎
⚘ ⚘
༻
#include <algorithm>
...
int a[3] = {2, 6, 4};
std::sort(a, a+3);
std::string b = "hello";
std::sort(b.begin(), b.end());
是確使使用者可在容器物件(container,例如連結串列或陣列)上遍訪的物件。(節自維基百科)
༻
#include <algorithm>
...
int a[3] = {2, 6, 4};
std::sort(a, a+3);
std::string b = "hello";
std::sort(b.begin(), b.end());
a / &(a[0])
a+a的大小 / &(a[a的大小-1])+1
a.begin() | a.begin()+1 | a.begin()+2 | a.begin()+3 | a.begin()+4 | a.end() |
---|---|---|---|---|---|
h | e | l | l | o |
⸎
⚘ ⚘
⸎
⚘ ⚘
⸎
⚘ ⚘
༻