C++/Data Type/String
Версия от 14:21, 25 мая 2010; (обсуждение)
Содержание
- 1 Accessing Characters In Strings
- 2 Adding Strings
- 3 A filter to remove white-space characters at the ends of lines.
- 4 A short string demonstration
- 5 A string demonstration: assignment, concatenate, compare
- 6 Demonstrate insert(), erase(), and replace().
- 7 Inputting Multiple Words into a String
- 8 Insert, search, and replace in strings.
- 9 Print a name in two different formats
- 10 Read string from console
- 11 Several string operations: substr
- 12 String Char Indexing
- 13 String Find and replace
- 14 string: find( ) and rfind( )
- 15 String insert(), erase(), and replace()
- 16 String Size
- 17 String SizeOf
- 18 Strings: size, iterator, count, begin and end
- 19 String type class
- 20 string variable instead of a character array
- 21 Use string: find, string::npos
Accessing Characters In Strings
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string text;
cout << "Counts words. Enter a text and terminate with a period and return:\n";
getline( cin, text, "."); // Reads a text up to the first "."
int i, // Index
numberOfWhiteSpace = 0, // Number of white spaces
numberOfWords = 0; // Number of words
bool fSpace = true; // Flag for white space
for( i = 0; i < text.length(); ++i)
{
if( isspace( text[i]) ) // white space?
{
++numberOfWhiteSpace;
fSpace = true;
}
else if( fSpace) // At the beginning of a word?
{
++numberOfWords;
fSpace = false;
}
}
cout << "\nYour text contains (without periods)"
<< "\ncharacters: " << text.length()
<< "\nwords: " << numberOfWords
<< "\nwhite spaces: " << numberOfWhiteSpace
<< endl;
return 0;
}
Adding Strings
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string firstName = "gggg";
string lastName = "uuuut";
cout << "Your name is " << firstName + lastName;
return 0;
}
A filter to remove white-space characters at the ends of lines.
#include <iostream>
#include <string>
using namespace std;
void cutline( void );
string line;
int main()
{
while( getline(cin, line)) {
cutline();
cout << line << endl;
}
return 0;
}
void cutline()
{
int i = line.size();
while( i-- >= 0 )
if( line[i] != " " && line[i] != "\t" )
break;
line.resize(++i);
}
A short string demonstration
#include <iostream>
#include <string>
using namespace std;
int main()
{
string stringObject1("stringObject1");
string stringObject2("stringObject2");
string stringObject3("stringObject3");
string stringObject4;
stringObject4 = stringObject1;
cout << stringObject1 << "\n" << stringObject3 << "\n";
stringObject4 = stringObject1 + stringObject2;
cout << stringObject4 << "\n";
stringObject4 = stringObject1 + " to " + stringObject3;
cout << stringObject4 << "\n";
if(stringObject3 > stringObject1)
cout << "stringObject3 > stringObject1\n";
if(stringObject3 == stringObject1+stringObject2)
cout << "stringObject3 == stringObject1+stringObject2\n";
stringObject1 = "This is a null-terminated string.\n";
cout << stringObject1;
string str5(stringObject1);
cout << str5;
cout << "Enter a string: ";
cin >> str5;
cout << str5;
return 0;
}
A string demonstration: assignment, concatenate, compare
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1("Alpha");
string str2("Beta");
string str3("Omega");
string str4;
str4 = str1;
cout << str1 << endl << str3 << endl;
str4 = str1 + str2; // concatenate two strings
cout << str4 << endl;
str4 = str1 + " to " + str3;
cout << str4 << endl;
if(str3 > str1) // compare strings
cout << "str3 > str1\n";
if(str3 == str1 + str2)
cout << "str3 == str1+str2\n";
str1 = "This is a null-terminated string.\n";
cout << str1;
// create a string object using another string object
string str5(str1);
cout << str5;
// input a string
cout << "Enter a string: ";
cin >> str5;
cout << str5;
return 0;
}
Demonstrate insert(), erase(), and replace().
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1("www.java2s.com");
string str2("STL Power");
cout << "Initial strings:\n";
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << "\n\n";
// insert()
cout << "Insert str2 into str1:\n";
str1.insert(6, str2);
cout << str1 << "\n\n";
// erase()
cout << "Remove 9 characters from str1:\n";
str1.erase(6, 9);
cout << str1 <<"\n\n";
// replace
cout << "Replace 8 characters in str1 with str2:\n";
str1.replace(7, 8, str2);
cout << str1 << endl;
return 0;
}
Inputting Multiple Words into a String
#include <iostream>
using namespace std;
#include <string>
int main(void)
{
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Your name is " << name;
return 0;
}
Insert, search, and replace in strings.
#include <iostream>
#include <string>
using namespace std;
string stringObject1 = "As 111 555 ...",
stringObject2 = "number ";
int main()
{
int pos = 0;
cout << "stringObject1 : " << stringObject1 << endl;
cout << "\nInserting in string: " << stringObject2 <<""<< endl;
pos = stringObject1.find("555");
if( pos != string::npos )
stringObject1.insert(pos,stringObject2);
cout << "stringObject1 : " << stringObject1 << endl;
cout << "\nTo erase remaining characters behind 555:"
<< endl;
pos = stringObject1.find("555");
if( pos != string::npos )
stringObject1.erase(pos + 3);
cout << "stringObject1 : " << stringObject1 << endl;
cout << "\nTo replace 111 by 222:"
<< endl;
pos = stringObject1.find("111");
if( pos != string::npos )
stringObject1.replace(pos, 4, "222");
cout << "stringObject1 : " << stringObject1 << endl;
return 0;
}
Print a name in two different formats
#include <iostream>
#include <string>
using namespace std;
const string FIRST = "First";
const string LAST = "Last";
const char MIDDLE = "M";
int main()
{
string firstLast;
string lastFirst;
firstLast = FIRST + " " + LAST;
cout << "Name in first-last format is " << firstLast << endl;
lastFirst = LAST + ", " + FIRST + ", ";
cout << "Name in last-first-initial format is ";
cout << lastFirst << MIDDLE << "." << endl;
return 0;
}
Read string from console
#include <iostream>
using namespace std;
int main(void)
{
int myWeight, myHeight;
string myName;
cout << "Enter your name: ";
cin >> myName;
cout << "Enter your weight in pounds: ";
cin >> myWeight;
cout << "Enter your height in inches: ";
cin >> myHeight;
cout << "Your name score is " << myName << "\n";
cout << "Your weight in pounds is " << myWeight << "\n";
cout << "Your height in inches is " << myHeight << "\n";
return 0;
}
Several string operations: substr
#include <iostream>
#include <string>
using namespace std;
int main()
{
string fullName;
string name;
string::size_type startPos;
fullName = "Full name";
startPos = fullName.find("name");
name = "Mr. " + fullName.substr(startPos, 8);
cout << name << endl;
return 0;
}
String Char Indexing
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str( "hello" );
char ch = str[0];
str[0] = "j";
ch = str. at( 0 );
str.at(0) = "h";
ch = str[ 1000 ];
return 0 ;
}
String Find and replace
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str( "a bc abc abcd abcde" );
string searchString( "hello" );
string replaceString( "ab" );
assert( searchString != replaceString );
string::size_type pos = 0;
while ( (pos = str.find(searchString, pos)) != string::npos ) {
str.replace( pos, searchString.size(), replaceString );
pos++;
}
cout << str << endl;
return 0;
}
string: find( ) and rfind( )
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
string stringObject1 = "Quick of Mind, Strong of Body, Pure of Heart";
string stringObject2;
i = stringObject1.find("Quick");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
stringObject2.assign(stringObject1, i, stringObject1.size());
cout << stringObject2;
}
cout << "\n\n";
i = stringObject1.find("Strong");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
stringObject2.assign(stringObject1, i, stringObject1.size());
cout << stringObject2;
}
cout << "\n\n";
i = stringObject1.find("Pure");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
stringObject2.assign(stringObject1, i, stringObject1.size());
cout << stringObject2;
}
cout << "\n\n";
// find list "of"
i = stringObject1.rfind("of");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
stringObject2.assign(stringObject1, i, stringObject1.size());
cout << stringObject2;
}
return 0;
}
String insert(), erase(), and replace()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string stringObject1("stringObject1");
string stringObject2("stringObject2");
cout << "Initial strings:\n";
cout << "stringObject1: " << stringObject1 << endl;
cout << "stringObject2: " << stringObject2 << "\n\n";
cout << "Insert stringObject2 into stringObject1:\n";
stringObject1.insert(6, stringObject2);
cout << stringObject1 << "\n\n";
cout << "Remove 9 characters from stringObject1:\n";
stringObject1.erase(6, 9);
cout << stringObject1 <<"\n\n";
cout << "Replace 8 characters in stringObject1 with stringObject2:\n";
stringObject1.replace(7, 8, stringObject2);
cout << stringObject1 << endl;
return 0;
}
String Size
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "0123456789";
cout << "The current capacity of the string is:" << str.size() << endl;
str.resize( 20 );
cout << "The new capacity of the string is:"
<< str.size() << endl;
cout << "The actual length of the string is: "
<< strlen( str.c_str() ) << endl;
cout << "The string object after resizing "
<< "to 20 a 10 character string: "
<< str << endl;
str += "hello";
cout << str << endl;
return 0;
}
String SizeOf
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << sizeof( "hello" ) << endl;
cout << sizeof( "hello there" ) << endl;
string stringObject1 = "hello";
string stringObject2 = "hello there";
cout << sizeof( stringObject1 ) << endl;
cout << sizeof( stringObject2 ) << endl;
char* s1 = "hello";
char* s2 = "hello there";
cout << sizeof( s1 ) << endl;
cout << sizeof( s2 ) << endl;
char c_arr[] = "how are you?";
cout << sizeof( c_arr ) << endl;
return 0;
}
Strings: size, iterator, count, begin and end
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str1("www.java2s.com");
string::iterator p;
unsigned int i;
// use size()
for(i = 0; i <str1.size(); i++)
cout << str1[i];
cout << endl;
// use iterator
p = str1.begin();
while(p != str1.end())
cout << *p++;
cout << endl;
// use the count() algorithm
i = count(str1.begin(), str1.end(), "i");
cout << "There are " << i << " i"s in str1\n";
p = str1.begin();
while(p != str1.end())
cout << *p++;
cout << endl;
return 0;
}
String type class
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class StringClass {
char *p;
int len;
public:
StringClass(char *ptr)
{
len = strlen(ptr);
p = (char *) malloc(len+1);
if(!p) {
cout << "Allocation error\n";
exit(1);
}
strcpy(p, ptr);
}
~StringClass() {
cout << "Freeing p\n"; free(p);
}
void show()
{
cout << p << " - length: " << len;
cout << endl;
}
};
int main()
{
StringClass stringObject1("www.java2s.com"), stringObject2("www.java2s.com");
stringObject1.show();
stringObject2.show();
return 0;
}
string variable instead of a character array
#include <iostream>
using namespace std;
#include <string>
int main(void)
{
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Your name is " << name;
return 0;
}
Use string: find, string::npos
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
string s1 = "Quick of Mind, Strong of Body, Pure of Heart";
string s2;
i = s1.find("Quick");
if(i != string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
s2.assign(s1, i, s1.size());
cout << s2;
}
cout << endl;
i = s1.find("Strong");
if(i != string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
s2.assign(s1, i, s1.size());
cout << s2;
}
cout << endl;
i = s1.find("Pure");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
s2.assign(s1, i, s1.size());
cout << s2;
}
cout << endl;
// find list "of"
i = s1.rfind("of");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
s2.assign(s1, i, s1.size());
cout << s2;
}
return 0;
}