Otaru C++ Single Chapter ④ Character Array and String

Table of contents

1. Characters and Arrays

1. Find the length of the character array

2. Find words

2. Strings and Arrays

2.1 String output in reverse order

2.2 String comparison

2.3 Uppercase letter output

Edit

3. Common string functions

1. Initialization string:

2. String operations: (add, delete, modify, check)

3. Intercept and replace strings

4. Replace a certain value in a string

4. Application questions

1.Suffix

2. Have fun at the beginning of school

3. Find the longest and shortest word


1. Characters and Arrays

String : A continuous string composed of multiple characters is a string.

Note the distinction between the character 'a' and the string "a"; the character is a single quote and the string is a double quote.

Character refers to a single character, and a string consists of any number of characters, such as "abc", "a 8A"

If we split a string:

For example : "hello"   is broken down into : 'h','e','1','1','o','\0'

It must be noted here that at the end of all strings, the system will automatically add a '\0' as the end, which means that a string with a length of 5 actually requires 6 units of space.

Insert image description here

1. Character array definition : char a[100];

2. Character array assignment : char b[100] = "hello";

b[0] =        b[1] =        b[2] =        b[3] =        

For character array input, you can directly use cin to input the value, and you do not need to input the for loop. This is a different characteristic from a one-dimensional array!


1. Find the length of the character array

'\0' represents the end of the string, and the loop judgment condition uses '\0'.

Seeing the above code, it is so troublesome to find the length of a string. Is there any simple way?

Import the library <cstring> and call the strlen() function to obtain the string length.

#include <iostream>
#include <cstring>
using namespace std;
int main() {
    char s[1000];   
    int len = 0;//int整数 
    cin >> s;//s="hello",以'\0'结尾 
    for(int i=0; s[i] != '\0'; i++){//s[0]='h',s[1]='e'
        len++;
    }
    cout << len << endl;//len=5
    
    int len2 = strlen(s);
	cout<<"长度2:"<<len2;
    return 0;
}


2. Find words

 

Find the number of times a certain word appears in a string. For example, the string hihellohi, "hi" appears 2 times.

#include <iostream>
#include <cstring>
using namespace std;
int main() {
    char s[] = {"hi"};
    char a[1000];
    int ans = 0;
    cout<<"请输入字符串:"; 
    cin >> a; // hihellohi
    int len=strlen(a);
    for(int i=0;i<len-1;i++){//选取开始对比位置
        bool flag = true;
        for(int j=0;j<2;j++){   //从第a[i]个开始对比
            if(a[i+j]!=s[j]){       //发现没有匹配上
                flag = false;       //标记没配对上
                break;              //结束循环
            }
        }
        if(flag == true){
            ans++;
        }
    }
    cout <<"匹配相等有:"<< ans << endl;
    return 0;
}


2. Strings and Arrays

1. Character array definition : string s;

2. Character array assignment : string b = “hello”;

b[0] =        b[1] =        b[2] =        b[3] =        

3. String length : Similar to character arrays, import the library <string> and use the variable name .size().

For example: s.size()

2.1 String output in reverse order

For example, if you input "hello", the output in reverse order is: "olleh".

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s;
	cin>>s;
	cout<<"长度:"<<s.size()<<endl; 
	for(int i=s.size()-1;i>=0;i--){
		cout<<s[i];
	} 
	return 0; 
} 

2.2 String comparison

Rules : Look at the two strings from left to right; compare the first character first, and compare the size through the ASCII code. If the first letters of the two strings are inconsistent, then whichever character is bigger means which string is bigger! It has nothing to do with the string length. When the characters at the same position are consistent, continue to compare until the comparison is completed, and then see which string is longer.

For example:

Which is greater, Abc or Abd?        

Which one is bigger, Abcd or Bab?        

Which is greater, Abcd or Abcde?        

Please input two strings s1 and s2; compare the sizes of the two strings. If s1>s2, output >, otherwise if s1=s2, output =, otherwise output <. And it is necessary to achieve repeatable and continuous comparisons!

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1, s2;
    while(1){
        cin>>s1>>s2;
        if(s1>s2){
            cout<<s1<<'>'<<s2<<endl;
        }if(s1<s2){
            cout<<s1<<'<'<<s2<<endl;
        } if(s1==s2){
            cout<<s1<<'='<<s2<<endl;
        }
    }
    return 0;
}

2.3 Uppercase letter output

Input a string and output the uppercase letters in the string.

#include <iostream>
#include <string>
using namespace std;
int main(){
//	输入字符串s1,有大小写,只输出大写字母
	string s1;
	cin>>s1;
	for(int i=0;i<s1.size();i++){
		if(s1[i]>='A' && s1[i]<='Z'){
			cout<<s1[i]<<" ";
		}
	} 
	return 0;
}

Read and concatenate strings across entire lines

getline(), reads the entire line (with spaces) of the string.

We know that inputting a string, separated by spaces, and then inputting a string means inputting two strings. But what if we need to enter spaces in the string itself?

Format: getline(cin, variable);

Use + to concatenate strings  s1 + s2.

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main(){
	string s;
	getline(cin,s);
	string s2="I am good";
	cout<<endl<<s+s2; 
}


3. Common string functions

1. Initialization string:

  1. Import library include<string>
  2. Definition and assignment

Define a string: string s = “hello jxz”;

2. String operations: (add, delete, modify, check)

Search operation : find function search

Format: variable name.find("search word"), if available, returns the index position of "search word".

If the find function is not found, it will return string::npos . You can use if to determine whether it is found.

#include<iostream>
#include<string>
using namespace std;
int main(){
	string s;
	cin>>s; // hihellohello 
//	字符串的增删改查
//	 用法:变量名.find("查"),返回一个索引 
	cout<<s.find("he")<<endl; 	//输出索引位置 
	cout<<s.find("llo")<<endl;  //输出索引位置
	
	if(s.find("hllo") != string::npos){ //找得到的意思 
		cout<<s.find("hllo");
	}
	else{
		cout<<"找不到"; 
	}
    return 0;
}

Insertion operation : variable name.insert(index, value)

cout << s.insert(2,“hi”); //Insert at index 2

s.insert(0, "before"); // Insert at the first position

s.insert(s.size(), "end"); // Insert at the end

Exercise 1 : Define the string array s[2]; enter the first and second string.

Find whether the first string s[0] contains the second string s[1], if so, output the position, otherwise output NO.

    string s[2];
    cin>>s[0]>>s[1];
    if(s[0].find(s[1]) != string::npos){
    	cout<<s[0].find(s[1]);
	}
	else{
		cout<<"NO!";
	}

 Exercise 2: Define an array that stores three string names, loop through the input values; add the string Mr. to its 0th position, and finally output the latest result.

    string names[3];
	for(int i=0;i<3;i++){
		cin>>names[i];
		names[i].insert(0,"Mr. ");
	} 
	for(int i=0;i<3;i++){
		cout<<names[i]<<" ";
	}

Exercise 3: Digital signature is a way to encrypt text. Next, we will use the learned string insertion and search functions to encrypt a string of text. If the number 66 appears in this string of text, insert "jiami" before the first 66; otherwise, the original text will be output.

//Digital encryption

    string text;
    cin >> text;
    if(text.find("66") != string::npos){
    	cout<<text.insert(text.find("66"),"jiami")<<endl;
	}
	else{
		cout<<text;
	}


3. Intercept and replace strings

Intercept a short section of string :  s.substr(position, length)

Define string string s = "eat good!"; We only need part of the string good!

cout<<s.substr(4);

cout<<s.substr(0,3); //We only need to get the intercepted length of eat 3

Exercise 4: Operate on the above name string. Here, we hope to intercept and output the 2nd to 6th characters of each read string. After reading each string, assign each string to the intercepted result.

string names[3];
for (int i = 0; i < 3; i++) {
        cin >> names[i];
        names[i]=names[i].substr(1,5);
    }
    for (int i = 0; i < 3; i++) {
        cout << names[i] << endl;
}


4. Replace a certain value in a string

 s.replace(position, length, "replacement value");

Exercise 5: Then turn the above interception operation into a replacement operation; replace the 2nd to 6th characters of the string with "ABC".


   string names[3];
    for (int i = 0; i < 3; i++) {
        cin >> names[i];
        names[i].replace(1,5,"ABC");
    }
    
    for (int i = 0; i < 3; i++) {
        cout << names[i] << endl;
}

Exercise 6: String s = "13sb344sbhsbjksbk", the output should eliminate spaces. Result: 13344hjkk

  1. 1. Idea: After defining the variable s, loop: satisfy s.find(" ") != string::npos to execute the program
  2. 2. Use replace() to replace the spaces " " with "". Finally, the loop ends and the string s is output.
    string s = "13 344 h jk k";
	for(int i=0;s.find(" ") != string::npos;i++){
		s = s.replace(s.find(" "),1,"");
	}
	cout<<s;
	return 0;

4. Application questions

1.Suffix

#include<iostream>
using namespace std;
int main(){
	string s;
	cin>>s;
	int len = s.size();
	if(s[len-2]=='e' && s[len-1]=='r'){
		for(int i=0;i<len-2;i++){
			cout<<s[i];
		}
	}
	else if(s[len-2]=='l' && s[len-1]=='y'){
		for(int i=0;i<len-2;i++){
			cout<<s[i];
		}
	}
	else if(s[len-3]=='i' && s[len-2]=='n' && s[len-1]=='g'){
		for(int i=0;i<len-3;i++){
			cout<<s[i];
		}
	}
	else{
		cout<<s;
	}
	return 0;
}


2. Have fun at the beginning of school

 

 

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s;
    cin >> s;
    for(int i=0;i<s.size();i++){
        string a = s.substr(i,3);
        if(a[0]==a[1]&&a[1]==a[2]){
            //cout<<a<<endl;
            s.replace(i,3,"");
            i=-1;
        }
    }
    cout<<s;
}

 

3. Find the longest and shortest word

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s;
    cin >> s;
    for(int i=0;i<s.size();i++){
        string a = s.substr(i,3);
        if(a[0]==a[1]&&a[1]==a[2]){
            //cout<<a<<endl;
            s.replace(i,3,"");
            i=-1;
        }
    }
    cout<<s;
}

Guess you like

Origin blog.csdn.net/weixin_44775255/article/details/129381483