Содержание:
Theory
String type
- To work with a string the
string
library must be included: - Variables of string type can be understood as an array of characters.
- A specific character in a string can be accessed as in a regular array, that is, by its index:
#include <string> |
string str="it's possible to understand it"; cout << str[2] << endl; // output: ' for (int i = 0; i <= str.size(); i++) { // to iterate over the characters of a string if (str[i] == ' ') //to do sth } |
String functions
size_t find
(const string& str, size_t pos = 0) const;
pos
is specified, the search only includes characters at or after positionpos
, ignoring any possible occurrences that include characters before pos
.
size_t
is an unsigned integral type, able to represent the size of any object in bytessize_t
(usually = 4294967295)len
(or sublen) parameter in string’s member functions, means «until the end of the string».size_t
is an unsigned integral type, it is the largest possible representable value for this type.string str="it's possible to understand it"; string substr="it"; size_t f = -1; int counter = 0; while (true) // infinite loop { // f = str.find(substr); // f will be equaled to 0 // 'f+1' is required to move to the next position after found match f = str.find(substr, f+1); // in the 2-nd iteration f = 28 // in the 3-rd iteration f = 4294967295, it means that there is no more matches // string::npos = 4294967295 if (f == string::npos) break; counter++; } cout << counter; |
Escape sequences are used to represent certain special characters within string literals and character literals: \
‘ single quote
char c = '\'' |
Strings as char and pointers
\0
). char s[6] = "Hello"; // \0 is added automatically char s[] = "Hello"; // the same reuslt char* p = s; // H |
To iterate over the string characters:
char* p = s; while (*p != 0) cout << *p++; |
or
char* p = s; while (*p) cout << *p++; |
Labs and tasks
To do all the tasks and labs of this lesson you must create three files:
- a header file (
basicStrings.h
) (functions definitions for all the tasks must be placed here); - a
basicStrings.cpp
file (the implementations of the functions with comments for all the tasks must be placed here) - a
main.cpp
must provide prompts for user, calling created functions and output results for all the tasks. - Each function should be accompanied by a comment about what it is intended for, and a number of the task must be provided.
String type
To do: A string type variable (s="Hello world"
) is given and character (variable c
) is given (ask user to input it). Check if the character c
is among the characters of the string. Create a function named checkIfChar
to do the task. The function must return 1
if entered character is found or 0
otherwise.
Note 1: The signature of the function must be as follows:
bool checkIfChar(string s, char c) |
Expected output:
lab 1 A sentence is "Hello world" Enter character: >>> o result: 1
✍ Algorithm:
- Open visual studio and create a console application named
Lesson6
. While creating, check the Empty project (Пустой проект) item. - Two
.cpp
files must be added to the source files folder of the project (basicStrings.cpp
andmain.cpp
) and one header file must be added to the Header files folder. - Open the
main.cpp
file’s code and add all the libraries we need to do the lab: - Inside the
main
function, ask user to input a sentence and assign the input value tostr
variable. Don’t forget to declare the variable: - Then, ask user to input a character to find it in the sentence. Set the input value to a variable
c
: - Now, we’re going to create a function to check if the input charecter is within the input sentence. The function must be supplied with two values — the sentence (
str
) and character (c
), they are the arguments of the function. Add the signature of the function before the main function: - We’re going to itereate over the characters of the string using
for
loop. Inside the the loop body we must check if a current character of the string matches the characterc
. If it does, the function must return1
, in the case when it doesn’t, the function returns0
. - Come back to the
main
function code and call the function. The results of the function must be printed out, so, the calling should be insidecout<<
statement: - Be careful not to forget to add a statement to stay the console window opened:
- Run the program and check the output.
#include#include using namespace std;// #include // is needed to work with string type
int main() { cout << "lab 1:" << endl; string str="Hello world"; // declaration of the variable // .. }
cout << "Enter character :" << endl; char c; cin >> c;
//lab 1: Check if the character c is among the characters of the string bool checkIfChar(string s, char c) { // to do }
for (int i=0;i<= s.size();i++){ if (s[i]==c){ return 1; break; } } return 0;
cout << "result :" << checkIfChar(str, c) << endl;
//... system("pause"); return 0; //...
To do: Create a function to check if input text contains a combination of letters 'mo
'. Return 1
(if found) or 0
(if not found). It is not allowed to use any standard functions. To store the text, you should use a string type variable.
Note 1: The signature of the function must be as following:
bool findMo(string s) |
Note 2: To check two or more conditions in if
statement you must use &&
(logical and):
if (condition_1 && condition_2){ } |
Expected output:
task 1 result for 'Hello world' is: 0 --- task 1 result for 'My mom' is: result: 1
To do: Create a function to check if the value of string variable contains the word 'dog
'. Return 1
(if found) or 0
(if not found). You should use c character string
and a pointer. It is not allowed to use any standard functions.
Note 1: The signature of the function must be as following:
bool findMo(char* p) |
Expected output:
task 2 the string is: Hello world result: 0 --- task 2 Enter a sentence: the string is: my dog is nice result: 1
To do: A sentence is given: str = "word1 word2 word3 word4"
. Calculate the number of words in it. It is not allowed to use any string standard functions.
Note 1: You have to count the number of words by the number of spaces between the words.
Note 2: Don't forget to check if the sentence contain extra spaces at the beginning and end of the sentence.
Note 3: The signature of the created function must be as following:
void countWords(string s, int& counter) |
Expected output:
task 3 Enter a sentence: >>> word1 word2 word3 word4 result: 4
To do: A string is given. Check if its first and last characters match. Create a function named LastAndFirst
to do the task. It is not allowed to use any string standard functions (except size()
function).
Note 1: The signature of the created function must be as following:
bool LastAndFirst(string s) |
Note 2: The size()
method of the string can be useful to find the last character (s.size()
).
Expected output:
task 4 for sentence Hello world the result is: false --- task 4 for sentence lucky ball result is: true
String functions
To do: Create a function to check if the text contains the word cat
. Print the position (order number) of the word in the text. You should use standard find function.
Note 1: The signature of the created function must be as follows:
void findCatFunction(string s, string s0) |
Note 2: About find()
function:
s.find(s0) // returns -1 if there are no matches of s0 in the text s |
Expected output:
task 5 for text: cat word1 word3 word4 result : cat is found at: 0 --- task 5 for text: word1 word3 word4 result : cat is not found --- task 5 for sentence: word1 cat word3 word4 result : cat is found at: 6
To do: Two strings S
and S0
are given (they are entered). Find the number of occurrences of the string S0
in the string S
.
Note 1: In the solution, it is convenient to use the find member function of the string class, which returns the position of the occurrence of type size_t
(unsigned integer), or the value of string :: npos
in case no occurrence was found. Look at the example to understand the way to use them.
Note 2: The signature of the function must be as follows:
int countOccurrence(string s, string s0) |
Expected output:
Lab 2 string 1: it's possible to understand it string 2: it result : 2
✍ Algorithm:
- Open
main.cpp
file and inside themain
function, under the previous task code, add the code to output the number of the task. After that, declare the variables of string type and initialize them with values: - Open the implementation file, that is
basicStrings.cpp
. Add the code of the signature of the function, and also, add comments with explanation of the task: - The function must return integer type (since
int
is the type of the function). - The function has two parameters of string type:
s
is a string containing the sentence, ands0
is a substring which we must find inside the strings
. - To find the substring we're going to use the
find()
standard method andf
variable ofsize_t
type (an unsigned integral type). Thef
variable will store the position of the substring inside thes
string. And if there isn't founded substring thef
will store 0 number, since it will be increase by 1 (f+1
). When thefind()
function will reach the end of the string, the npos value (npos
is a constant — maximum value forsize_t
(usually = 4294967295)) will be set tof
variable: - Let's return to the
main.cpp
file and inside themain
function add the call of our function. Since the function will return the integer value, that is the number of occurrences, we must store the results of the function inside the variable: - Run the program and see the outputs.
//lab 2 cout << "lab 2:" << endl; string str1, str2; str1 = "it's possible to understand it"; str2 = "it"; cout << "string 1: " << str1 << "\n string 2: "<< str2 << endl;
\n
is used to insert a new line.// lab 2: Find the number of occurrences of the string S0 in the string S int countOccurrence(string s, string s0) { // to do: }
size_t f = -1; int res = 0; // counter of the numbers of occurrences while (true) // infinite loop { f = s.find(s0,f+1); if (f == string::npos) // if the end of the string is reached break; // exit loop ++res; } return res;
break
operator will be executed only if when seeking the substrings, we will reach the end of the string.int counter = countOccurrence(str1, str2); cout << "result :" << counter << endl;
To do: The strings S
and S0
are given. Create a function to remove the last substring that matches S0
from the S
string. If there are no matching substrings, then return the unchanged S
string.
Note 1: You can use the rfind member function of the string class to find the last occurrence of a substring, and you can use the erase member function to delete.
Note 2: Look at the example to understand the way to use them.
Note 3: The signature of the function must be as follows:
string eraseLast(string s, string s0) { // to do: // // return s; } |
Expected output:
task 6: string 1: it's possible to understand it string 2: it result: it's possible to understand
To do: A string containing at least one space character is given. Return the substring between the first and last spaces of the string. If the string contains single space, an empty string must be returned.
Note 1: You can use the substr member function of the string class to extract a substring.
Note 2: Look at the example to understand the way to use them.
Note 3: The signature of the function and the fragment of its code:
string betweenSpaces(string s) { size_t f1, f2; f1 = s.find(" "); // the position of the first space f2 = s.rfind(" "); // the position of the last space // ...; // ...; return // ...; } |
Expected output:
task 7: string: it's possible to understand it result : possible to understand
Note: задания следует сохранить в файле с именем задания, и обязательно в коде вставить комментарий с постановкой задачи.
STRING:
String13. A string is given, find the amount of digits in the string.
String28. A character
C
and a string S
are given, double each occurrence of the character C in the string S.String35. Two strings
S
, S0
are given. Remove all occurrences of S0
from the string S
. If the string S
does not contain required substrings then do not change it.String43. A string that contains English words separated by one or more blank characters is given. All string letters are in uppercase. Find the amount of words containing at least one letter "E".
String61. A string that contains a fully qualified path name (that is, the drive and directory parts, the file name and extension) is given. Extract the last directory name (without backslashes "
\
") from the string. If the file with the given name is located in the root directory then output a backslash.