Example: convert a date in the U.S. format to an international format.
Tip: U.S. date format: octomber
International Date Format: 01 octomer 2012
Because I feel more interested and impressed when I look at the code first and then think carefully about the usage of the function, because the reader will go deep into it, instead of looking at the function first and then creating it again, it will be boring to look at the function usage first, so the program is given before introducing the method
Code:
# Include <iostream>
# Include <string>
Using namespace STD;
Void main ()
{
Cout <"Enter the date in American format (e.g., December 25,2002 ):";
// Define the string variable date and input the date through the keyboard
String date;
Getline (CIN, date, '\ n ');
// Use the find function of the string class to find the space between the month and the date, and return the position to the variable I
Int I = date. Find ("");
// Define a string variable month. Use the substr function of the string class to intercept the month and return it to the month.
String month = date. substr (0, I );
// Search for and extract the date
Int K = date. Find (",");
String day = date. substr (I + 1, k-i-1 );
// Extract the year
String year = date. substr (k + 1, 4 );
// Define the string variable newdate to record the international format
String newdate = day + "" + month + "" + year;
// Output the US Date Format
Cout <"original date:" <date <Endl;
// Output International Date Format
Cout <"converted Date:" <newdate <Endl;
}
Running result:
After carefully analyzing the code, I believe you can also guess the usage and functions of the find and substr member functions of the string class. When you have a preliminary understanding of them, the following describes their usage.
Let's talk about the find function first.
Format: Object Name. Find (the string to be searched and the position to start searching)
This member function returns the position of the searched string in the main string. There is only one form parameter in the Code. The location parameter is omitted. If it is omitted, the default location parameter is 0, you can write the find function in the Code as follows:
Int I = date. Find ("", 0 );
Int K = date. Find (",", 0 );
What can be found above? What if the target string cannot be found? The system returns-1 by default if it cannot be found.
Here we will introduce the find function. I believe you will be able to draw the opposite line. Next we will introduce the substr function.
Format: Object Name. substr (string position, truncation length)
This member function is used to return the string. The code is used very well, but what if the length is greater than the string length? The system thinks this is acceptable and will automatically intercept it to the end.
There are also many member functions in the string class. To learn more and learn more, you must perform multiple practical operations. It is very suitable for programming. This is the case.