Scribbling

[C++] 전문가를 위한 C++ - Chapter 2 본문

Computer Science/C++

[C++] 전문가를 위한 C++ - Chapter 2

focalpoint 2023. 9. 21. 00:38

1. String

substr(pos, len)

find(str)

replace(pos, len, str)

starts_with(str)

ends_with(str)

int main() {

	string str{ "Hello!" };

	if (str.find("!") != string::npos) {
		cout << str << endl;
	}

}

 

2. Number to String

int main() {

	long double d{ 3.14L };
	string s{ to_string(d) };

}

 

3. String to Number

int stoi(const string& str, size_t* idx=0, int base=10);

long stol(const string& str, size_t* idx=0, int base=10);

...

 

4. String_view

string_view is a new feature in C++17 - it is an efficient method to get a substring of the given string; it does not copy the string nor can modify it.

string_view func(string_view sv) {
	return sv.substr(sv.rfind('.'));
}

int main() {
	string filename{ "C:\\temp\\my file.txt" };
	cout << func(filename) << endl;
	cout << "string"s + func(filename).data() << endl;

}

 

5. format

int main() {
	
	int i{ 10 };
	auto s2{ format("Read {0} bytes from {1}", i, "file1.txt" )};
	cout << s2 << endl;
}