Simple String Handling

Notice: The new book " Algorithm Competition " I wrote in two years has been handed over to Tsinghua University Press in February 2022 and is expected to be published in July 2022. "Algorithm Competition" is a " compendium ", covering "basic - intermediate - advanced", about 700 pages in length. Drafts of some knowledge points have been published on this blog.


   Simple string problems, that is, simple problems that do not involve complex string algorithms. It is very common in the Blue Bridge Cup provincial competition, almost every edition .
   String algorithms include: binary hash, Manacher, dictionary tree, palindrome tree, KMP, AC automaton, suffix tree and suffix array, suffix automaton, which will be analyzed in detail in the upcoming "Algorithm Competition" .
   This article introduces the string processing functions of C++, Java, and Python . Finally, some exercises are given, and it is the most important to practice these problems by yourself .

1. C++ string functions

  find() function: find
  substr() function: check substring
  replace() function: replace
  insert() function: insert
  append() function: add string
  swap() function: exchange strings
  compare(): string comparison
  has When there are spaces in a line of characters entered, you can use gets() to read the line including spaces.
  The executable code below demonstrates the application of these functions.

#include<bits/stdc++.h>
using namespace std;
int main(){
    
    
    string str ="123456789abcdefghiaklmn";

    for(int i=0;i<10;i++)   //把str看成一个字符串数组
        cout<<str[i]<<" ";
    cout << endl;

//find函数
    cout<<"123的位置:   "<<str.find("123")<<endl;
//输出:123的位置:   0
    cout<<"34在str[2]到str[n-1]中的位置:   "<<str.find("34",2)<<endl;
//输出:34在str[2]到str[n-1]中的位置:   2
    cout<<"ab在str[0]到str[12]中的位置:    "<<str.rfind("ab",12)<<endl;
//输出:ab在str[0]到str[12]中的位置:    9

//substr()函数
    cout<<"str[3]及以后的子串:"<<str.substr(3)<<endl;
//输出:str[3]及以后的子串:456789abcdefghijklmn
//若小于限制长度则报错
    cout<<"从str[2]开始的4个字符:"<<str.substr(2,4)<<endl;
//输出:从str[2]开始的4个字符:3456

//find()函数
    str.replace(str.find("a"), 5, "@#");
    cout<<str<<endl;
//输出:123456789@#fghiaklmn

//insert()函数
    str.insert(2, "***");
    cout<<"从2号位置插入: "<<str<<endl;
//输出:12***3456789@#fghiaklmn

//添加字符串:append()函数
    str.append("$$$");
    cout<<"在字符串str后面添加字符串:"<<str<<endl;
//输出: 12***3456789@#fghiaklmn$$$

//字符串长度
    cout<<str.size()<<endl;
    cout<<str.length()<<endl;

//交换字符串:swap()函数
    string str1="aaa",str2="bbb";
    swap(str1, str2);
    cout<<str1<<"  "<<str2<<endl;

//字符串比较函数:compare(),相等输出0,不等输出1
    cout<<str1.compare(str2)<<endl;
    if(str1==str2) cout <<"==";   //直接比较也行
    if(str1!=str2) cout <<"!=";

    return 0;
}

2. Python string processing

  Python's character handling is very concise. The executable code below gives examples of various applications.

str1="12345678abcdefghi"
print(str1)      #输出:12345678abcdefghi
print(str1[3])   #输出:4
print(str1[2:5]) #输出:345       截取一部分,左闭右开
print(str1[:5])  #输出:12345
print(str1[2:])  #输出:345678abcdefghi
print(len(str1)) #输出字符串长度: 17

str2="***"
str3="abc"
#合并字符串:+
str12=str1+str2
print(str12)                 #输出:12345678abcdefghi***
#也可以这样合并字符串
print(''.join([str1, str2])) #输出:12345678abcdefghi***

str_list = list(str1)
str_list.insert(4, "***")     #在str1[4]插入
aa = ''.join(str_list)
print(aa)                     #输出:1234***5678abcdefghi

#重复输出
print(str2*2) #输出:******

#用\输出特殊符号
print("\\    \"    \n ")      #输出:\ "  换行

#查找子串
print(str3 in str1)           #输出:True
print(str3 not in str1)       #输出:False

str2,str3 = str3,str2         #交换
print(str2)                   #输出:abc

#比较
print(str2 == str3)           #输出:False
print(str2 != str3)           #输出:True

#str.find(str, beg=0, end=len(string))   指定范围查找
print(str1.find("345"))         #输出:2
print(str1.find("345", 10))     #输出:-1
print(str1.find("456", 2,20))   #输出:3

3. Java String Functions

  Java's string processing functions are very rich. A description of some functions is given below.
  (1) substring()
  returns the substring at the specified position. There are two forms:
  String substring(int startIndex), start index (including startIndex), index starts from 0.
  String substring(int startIndex,int endIndex)
start index (including startIndex), the index starts from 0; end index (excluding endIndex).

String Str = new String("This is haha");
System.out.println(Str.substring(4) );      //输出:is haha
System.out.println(Str.substring(4, 10) );   //输出:is ha

(2) concat()
  public String concat(String s)
  connects s ​​after the string and returns a new string.

String s = "www:";
s = s.concat("abcde.com");
System.out.println(s);   //输出:www.abcde.com

  (3) replace()
  replaces.
  public String replace(char searchChar, char newChar)
  Replaces all occurrences of searchChar characters in a string with newChar characters and returns the new string after replacement.

String Str = new String("abcde");
System.out.println(Str.replace('c', 'T'));  //输出:abTde

  (4) trim()
  deletes the leading and trailing spaces of the string.
  (5) valueOf()
  returns the value of the given parameter, which can be a native data type, String, etc.
  static Integer valueOf(int i)
  static Integer valueOf(String s)
  static Integer valueOf(String s, int radix)

Float a = Float.valueOf("80"); 
System.out.println(a);        //输出:80.0

  (6) toLowerCase()
  converts to lowercase
  char toLowerCase(char ch)

System.out.println(Character.toLowerCase('a'));     //输出:a
System.out.println(Character.toLowerCase('A'));     //输出:a

  (7) toUpperCase()
  converts to uppercase
  public String toUpperCase()

String Str = new String("www.com");
System.out.println( Str.toUpperCase() );    //输出:WWW.COM

  (8) length()
  The length of the string

String Str1 = new String("www.com");
System.out.println(Str1.length());           //输出:7

  (9) charAt()
  intercepts a character
  public char charAt(int index)

String s = "www.com";
char result = s.charAt(6);
System.out.println(result);  //输出:m

  (10) getChars() intercepts multiple characters
  and copies the characters from the string to the target character array.
  void getChars(int sourceStart,int sourceEnd,char target[],int targetStart)
  sourceStart – The index of the first character in the string to copy.
  sourceEnd – The index after the last character in the string to copy.
  target Array of targets.
  targetStart The starting offset in the target array.

String Str1 = new String("www.abcde.com");
char[] Str2 = new char[6];
Str1.getChars(4, 10, Str2, 0);
System.out.println(Str2 );    //输出:abcde

  (11) equals() and equalsIgnoreCase()
  compare two strings
  (12) regionMatches()
  detects whether two strings are equal in a region.
  (13) startsWith() and endsWith()
  startsWith() checks whether the string starts with the specified string. endWith() checks if the string ends with the specified string.
  (14) compareTo() and compareToIgnoreCase()
  compare strings
  (15) indexOf() and lastIndexOf()
  indexOf() finds the first occurrence of a character or substring.
  lastIndexOf() finds the last occurrence of a character or substring.

4. Exercises

  Let's do some simple string problems, none of which involve algorithms or data structures. This kind of problem is more common in the Blue Bridge Cup provincial competition.
  Please do these questions yourself, this is the most important . If you want to look at the correct code, someone has posted a solution to each question , including C++, Java, and Python. The code is no longer posted in this article.

Title statisticshttps: //www.lanqiao.cn/problems/325/learning/Roman
numeralshttps : //www.lanqiao.cn/problems/276/learning/Delete
charactershttps : //www.lanqiao.cn/problems/ 544/learning/
minesweeper https://www.lanqiao.cn/problems/358/learning/lurkerhttps://www.lanqiao.cn/problems/519/learning ISBN
numberhttps : //www.lanqiao.cn The expansion of /problems/523/learning/ string https://www.lanqiao.cn/problems/536/learning/ FBI treehttps : //www.lanqiao.cn/problems/571/learning/Word Solitairehttps :/ /www.lanqiao.cn/problems/769/learning/stereogramhttps://www.lanqiao.cn/problems/526/learning/Calculator improvementhttps : //www.lanqiao.cn/problems/771/learning/ _






Processing of strings https://www.lanqiao.cn/problems/287/learning/Who
has won the most scholarshiphttps ://www.lanqiao.cn/problems/565/learning/Substring https ://www.lanqiao. cn/problems/365/learning/ expression evaluationhttps: //www.lanqiao.cn/problems/378/learningword analysishttps : //www.lanqiao.cn/problems/504/learningcounting wordshttps :/ /www.lanqiao.cn/problems/397/learning/table tennishttps://www.lanqiao.cn/problems/744/learning/Number of palindromeshttps : //www.lanqiao.cn/problems/774/learning/





Guess you like

Origin blog.csdn.net/weixin_43914593/article/details/123816703