Menghitung jumlah karakter String:
#include <iostream>
#include <string>
int main ()
{
std::string str ("Test string");
std::cout << "The size of str is " << str.length() << " bytes.\n";
return 0;
}
Merubah karakter String:#include <iostream>#include <string> int main (){std::string base="this is a test string.";
std::string str2="n example";
std::string str3="sample phrase";
std::string str4="useful.";
// replace signatures used in the same order as described above:
// Using positions: 0123456789*123456789*12345
std::string str=base;// "this is a test string."
str.replace(9,5,str2);// "this is an example string." (1)
str.replace(19,6,str3,7,6);// "this is an example phrase." (2)
str.replace(8,10,"just a");// "this is just a phrase." (3)
str.replace(8,6,"a shorty",7);// "this is a short phrase." (4)
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)
std::cout << str <<'\n';
return0;
}Mencetak Array to String
#include <iostream>
using namespace std;
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}
JOIN array dalam contoh (strcpy atau strcat):
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
// copy str1 into str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
// concatenates str1 and str2
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
// total lenghth of str1 after concatenation
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
return 0;
} //Greeting message: Hello
HASIL SAAT DI PLAY:strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
JOIN array dalam contoh (+):#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
// copy str1 into str3
str3 = str1;
cout << "str3 : " << str3 << endl;
// concatenates str1 and str2
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;
// total lenghth of str3 after concatenation
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
}Hasil saat di Play:
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
Tidak ada komentar:
Posting Komentar