C++ 33. String class in C++-Ditai Software Academy

The history of C strings

  • C language does not support true strings
  • C language uses character arrays and a set of functions to implement string operations
  • C language does not support custom types, so string types cannot be created

At that time, C language was mainly used to develop UNIX operating systems, and there were few cases of processing strings. Therefore, under the background of that time, there was no built-in string type in C language. Later, the C language became more and more widely used, and there was no other way but to use character arrays to simulate strings. When developing applications, there are many situations where strings are processed. If character arrays are also used to process strings, the development efficiency will be very low. Therefore, in C++, the concept of strings must be introduced.

C++ string solution

  • C++ also does not support true strings
  • C++ supports custom types
  • C++ can complete the definition of string type through classes
  • C++ is fully compatible with C, and C++ also supports the use of character arrays and a set of functions to implement string operations.

In C++, you can customize class types, define some member functions, and overload operators. Therefore, in C++, you can completely use class types to implement string types.

Does the native type system in C++ include string types?

  • C++ language directly supports all concepts of C language
  • There is no native string type in the C++ language.

The C++ standard library provides the string class type

This class type fully implements the concept of string

  • string supports string concatenation
  • string supports size comparison of strings
  • string supports string search and extraction
  • string supports insertion and replacement of strings

1. String concatenation:

#include <iostream>  
#include <string>  

using namespace std;

int main() 
{
    
    
    string str1 = "Hello";
    string str2 = "World";
    string str3 = str1 + " " + str2;
    cout << str3 << endl;
    cin.get();
    return 0;
}

Output: Hello World

2. String size comparison:

#include <iostream>  
#include <string>  
  
using namespace std;  
  
int main() 
{
    
      
    string str1 = "Apple";  
    string str2 = "Banana";  
    if (str1 < str2) 
        cout << str1 << " < " << str2 << endl; 
    else if (str1 > str2) 
        cout << str1 << " > " << str2 << endl; 
    else 
        cout << "字符相等." << endl;
    cin.get();
    return 0;  
}

Output: Apple < Banana

3. String search and extraction:

#include <iostream>  
#include <string>  

using namespace std;

int main() 
{
    
    
    string str = "Hello, World!";
    size_t pos = str.find("World"); // 查找字符串"World"的位置  
    if (pos != string::npos) 
    {
    
     
        // 如果找到了字符串"World"  
        string sub_str = str.substr(pos, 5); // 提取从位置pos开始的5个字符  
        cout << sub_str << endl;
    }
    else
        // 如果找不到字符串"World"  
        cout << "找不到字符串." << endl;
    cin.get();
    return 0;
}

Output: World

4. String insertion and replacement:

#include <iostream>  
#include <string>  

using namespace std;

int main() 
{
    
    
    string str = "Hello, World!";
    str.insert(7, "Beautiful "); // 在位置7插入字符串"Beautiful "  
    cout << str << endl;
    str.replace(7, 9, "Nice"); // 从位置7开始,替换9个字符为"Nice"  
    cout << str << endl;
    cin.get();
    return 0;
}

Output:
Hello, Beautiful World!
Hello, Nice World!

5. String sorting

#include <iostream>
#include <string>  

using namespace std;

//对字符串进行由小到大排序 选择排序
void SortString(string a[], int len)
{
    
    
	for (int i = 0; i < len; i++)
	{
    
    
		for (int j = i; j < len; j++)
		{
    
    
			if (a[i] > a[j])
			{
    
    
				swap(a[i], a[j]);
			} 
		}
	}
	return;
}

int main()
{
    
    
	string sa[5] = {
    
     "1","2","3","10","11" };
	SortString(sa, 5);
	for (int i = 0; i < 5; i++)
	{
    
    
		cout << sa[i] << endl;
	}
	cin.get();
	return 0;
}

Output:
1
10
11
2
3

  • >String comparison can be performed directly using
  • a[]As a function parameter, the first address of the array is passed, not a copy of the array, so the value of the array can be modified inside the function.
  • std::swap()Can be used to exchange the values ​​of two elements or objects. Can be used for any data type, including built-in types (for example: int, double) complex types (for example: classes, structures).

6. String concatenation

#include <iostream>
#include <string>

using namespace std;

string AddString(string a[], int len)
{
    
    
    string ret = "";

    for (int i = 0; i < len; i++)
    {
    
    
        ret += a[i] + "-";
    }

    return ret;
}

int main()
{
    
    
    string sa[5] =
    {
    
    
        "狄泰",
        "学院",
        "的",
        "同学们",
        "求个关注",
    };

    cout << AddString(sa, 5) << endl;
    cin.get();
    return 0;
}

Output
Ditai-college-students-please pay attention-

  • Use + for string concatenation
  • ret += a, equivalent to ret = ret + a
  • Operator overloading is quite common in the standard library, and the string class makes extensive use of string overloading.
  • In C++, there is no need to use a character array to simulate a string. Use the string class directly. In the code, the character pointer char* no longer appears.

Conversion of strings and numbers

  • The standard library provides related classes to convert strings and numbers.
  • The string stream class sstream is used for string conversion
  • The header file issstream
  • String input streamistringstream
  • String output streamostringstream

1.string -> number

#include <iostream>  
#include <sstream>  
#include <string>  
using namespace std;
int main() 
{
    
    
    string str = "3.14";
    // 定义字符串输入流,并传入一个str
    istringstream iss(str);
    // 定义一个double用于接收
    double num;
    if(iss >> num)
    	std::cout << "num: " << num << std::endl;
    cin.get();
    return 0;
}

Output: 3.14

  • iss >> numThere is a Boolean return value used to determine whether the transmission is successful.

2. Number -> string

#include <iostream>  
#include <sstream>  
#include <string>  
using namespace std;
int main() 
{
    
    
    // 定义字符串输出流
    ostringstream oss;
    int num = 123;
    oss << num;
    // 返回字符串
    string str = oss.str();
    cout << str << endl;
    cin.get();
    return 0;
}

Output: 123

  • Use oss.str()a string that returns the output stream.
  • oss << num;There is also a return value, which is the stream itself. oss << 123;Equivalent tooss <<1<<2<<"3";

3. Use macros to convert numbers and strings

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

#define TO_NUMBER(s, n) (istringstream(s) >> n)
#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str())

int main()
{
    
    
    double n = 0;

    if (TO_NUMBER("3.1415926", n))
        cout << n << endl;

    string s = TO_STRING(12345);

    cout << s << endl;
    std::cin.get();
    return 0;
}

Output
3.14159
12345

4. Overloaded the right shift operator ">>" to perform a circular right shift operation on the string

#include <iostream>  
#include <string>  

using namespace std;  
  
// 重载右移运算符">>"
string operator >> (const string& s, unsigned int n)  
{
    
      
    string ret = "";  
    unsigned int pos = 0;  
      
    // 使n对s的长度取模,防止n大于s的长度导致的无效右移  
    n = n % s.length();  
    // 计算开始切割的位置
    pos = s.length() - n;  
    // 从pos位置开始切割字符串,得到子字符串ret  
    ret = s.substr(pos);  
    // 从0位置开始切割字符串,得到子字符串tmp  
    string tmp = s.substr(0, pos);  
    // 将tmp添加到ret的尾部,完成循环右移操作  
    ret += tmp;  

    return ret;  
}  
  
int main()  
{
    
      
    string s = "abcdefg";  
    string r = (s >> 3);  
    cout << r << endl;  
    return 0;  
}

output
abcdefg
efgabcd

5. String reversal

Requirements:
“we;tonight;you” -> “ew;thginot;uoy”

#include <iostream>
#include <string>

using namespace std;

string reverse(const string& s, const char c)
{
    
    
    string ret = "";

    return ret;
}

int main()
{
    
    
    cout << reverse("", ';') << endl;                 // 输出:空字符串
    cout << reverse(";", ';') << endl;                // 输出:;
    cout << reverse("abcde;", ';') << endl;           // 输出:edcba;
    cout << reverse("we;tonight;you", ';') << endl;   // 输出:ew;thginot;uoy
    cin.get();
    return 0;
}

output

Guess you like

Origin blog.csdn.net/WangPaiFeiXingYuan/article/details/133337653