Sharing Key Points on C++ Strings

Review of char type,one-dimensional char arrays,string,common problem types. The organization of knowledge points is somewhat rough, but they are all key points that must be mastered. The knowledge points regarding string positions are quite detailed, and this area can test loops, arrays, and characters, making it a comprehensive topic. Therefore, strings are often tested in various competitions, not only focusing on these basic concepts but also assessing students’ overall problem-solving abilities.1. Review of char type

Definition

char c; // stores a single character, where a single letter, number, or other symbol enclosed in single quotes counts as a single character

Line breaks, tabs, and spaces also count as single characters that can be stored in a char type variable

Direct assignment

char a=’-‘; Note: it is single quotes!

Input a single character

1. cin>>a;

cin ignores line breaks, spaces, tabs, and other whitespace characters by default

2. scanf(“%c”,&a);

scanf can also handle the input of a single whitespace character

3. How to read line breaks, spaces, tabs, and other whitespace characters?

a=getchar(); reads a character from the keyboard and assigns it to a

Output a single character

cout<<a; printf(“%c”,a);

Essence of character storage All characters correspond to a unique number called the ASCII code to remember:

97->’a’

65->’A’

48->’0′

Lowercase letters – 32 = uppercase letters

Uppercase letters + 32 = lowercase letters

2. One-dimensional char arrays, two-dimensional

The usage can be compared to one-dimensional and two-dimensional arrays.

Definition

char c[10];

Direct assignment

char a[10]={‘y’,’u’,’a’,’n’}; Note: unassigned positions are automatically assigned ‘’

Input for character arrays

1. A line of string without spaces cin>>a; Note: input stops automatically at spaces scanf(“%s”,a); a is the array name, not a variable name, so no need to use &

2. A line of string with spaces: cin.getline(array_name, length); automatically adds ‘’ at the end of the string to indicate the end of the string

Output for character arrays

cout<<a;

printf(“%s”,a);

puts(s); // puts function is used to output strings and add a newline #include<cstdio>

  • Common function methods:

Note: header file <cstring>

  1. Get the length of the string strlen(a)

Get the length of the string stored in character array a

Note: the string starts storing from index 0 to strlen(a)-1;

  1. Compare the sizes of two strings strcmp(a,b)

Comparison is done in lexicographical order, based on ASCII codes

If a is larger, the result of the comparison is >0;

If a is smaller, the result of the comparison is <0;

If they are the same, the result is 0;

  1. strcpy(b,a); assigns string a to string b
  • Two-dimensional character arrays
  1. Definition: char a[10][20]; // rows columns

If you want to output the 5th string, you should use cout<<a[4];

  1. (Key point) Input and output of two-dimensional character arrays:
for(int i=0;i<=4;i++){  cin>>a[i];//cout<<a[i];}

string type

Import header file#include<string>

Definition

string s;

Direct assignment
  • Complete string assignment

1. Directly use the assignment operator =

2. Use the assign() function

  • Single character assignment

1. Using the subscript operator s[2]=’p’

// No out-of-bounds check, out-of-bounds does not report an error using at()

2. Function s.at(0)=’p’ // performs out-of-bounds check, out-of-bounds reports an error

Input for character arrays

1. Using cin for input: filters leading spaces, reads words, and ends input upon encountering spaces

2. Using getline(cin,s) function for input: getline() always filters out the newline character at the end of the line, inputting the entire line

Output for character arrays

cout<<a;

  • Common exam points: loop input for string

  1. Input filtering spaces while (cin>>s)

  2. Input filtering line breaks while (getline(cin,s))

After line break, input ctrl+z, then press enter to end.

  • Common functions for string type

Concatenation

1. Use + to concatenate

2. s1.append(string2, start_index, length) // takes string2 from start_index for the specified length and appends it to string1

Comparison

1. Use relational operators > >= < <= == !=

2. Use compare() function, where the string that comes later in lexicographical order is considered larger

Substring extraction

substring = string s.substr(start_index, length)

The substring function does not change the original string but returns the substring, which needs to be reassigned.

String swap

swap(string1, string2)

Get length

1. Use s.size() function

2. Use length() function

Search

1. string1.find(string2) // find string2 in string1

If found, returns the index of the first occurrence of the substring (counting starts from 0); if not found, returns `string::npos` (a special value, usually -1, but of type `size_t`, so it is actually a very large positive number)

2. string1.find(string2, index i) // starts searching for string2 from index i in string1

3. string1.rfind(string2) // finds the last occurrence of string2 in string1

Replace

string1.replace(start_index i, length len, string2) // in string1, replaces len characters starting from index i with string2

Insert

string1.insert(start_index i, string2) // inserts string2 at index i in string1

Delete

1. string.erase(start_index i) // deletes all characters after index i

2. string.erase(start_index, length) // deletes len characters after index i

Get head and tail pointers

s.begin(): gets the head position (pointer) of string s

s.end(): gets the tail position (the position after the last character) (pointer)

Sort

sort(start_address, end_address + 1): sorts the array in ascending order

sort(s.begin(),s.end()); // sorts the characters within the string

sort(s,s+n); // sorts n strings

Reverse

reverse(start_address, end_address + 1): reverses the array

reverse(s.begin(),s.end()); // reverses the characters within the string

reverse(s,s+n); // reverses n strings

Common problem types

  • Traverse string

Note that the for loop range goes from 0 to string length – 1

char one_dimensional_array_traversal: int len=strlen(s);for(int i=0;i<len;i++)string type traversal: int len=s.size();for(int i=0;i<s.size();i++)
  • <span><span>Convert uppercase letters to lowercase/lowercase to uppercase</span></span>
for(int i=0;i<len;i++){    if(s[i]>='A'&&s[i]<='Z'){        s[i]+=32;    }}// Convert uppercase to lowercase
for(int i=0;i<len;i++){    if(s[i]>='a'&&s[i]<='z'){        s[i]-=32;    }}// Convert lowercase to uppercase
  • Right shift or left shift x positions

Right shift x positions if(s[i]>='A'&&s[i]<='Z'-(x%26)){        s[i]+=x%26;}else{        s[i]=s[i]-26+x%26;}Left shift x positions if(s[i]>='A'+(x%26)&&s[i]<='Z'){        s[i]+=x%26;}else{        s[i]=s[i]+26-x%26;}
  • Compare sizes

char array === strcmp(a,b)string === relational operators

Learn a little more today, and you will have more possibilities tomorrow.Sharing Key Points on C++ Strings

Leave a Comment