C++ substr 截取子串

1. substr() 方法使用

string substr (size_t pos = 0, size_t len = npos) const;
pos: 截取初始位置(从头开始截取pos=0)
len: 截取字符长度
1 // using substr
2 string fullName = "Sheep Core";
3 string firstName = fullName.substr(0, 5);
4 string lastName = fullName.substr(6, 4);
5 cout << firstName << " " << lastName;

补充:

2. Java 中使用 substring:

public String substring(int beginIndex, int endIndex)
beiginIndex:截取初始位置(从头开始截取pos=0)
endIndex:截取字符结束位置(exclusive 不包含)
1 public static void main(String[] args) {
2         String fullName = "Sheep Core";
3         String firstName = fullName.substring(0, 5);
4         String lastName = fullName.substring(6, fullName.length());
5         System.out.println(firstName + " " + lastName);
6     }

3. Python 中使用 substring:

直接使用下标截取的方法:最简单!

1 name = "Sheep Core"
2 firstName = name[:5]
3 lastName = name[6:]
4 print(firstName + " " + lastName)

4. Summary:

C++ substr() 的两个参数分别是初始位置和长度,而Java中substring()的两个参数是初始位置(inclusive)和结束位置(exclusive)。

水滴石穿,笨鸟先飞!


原文地址:https://www.cnblogs.com/sheepcore/p/12377034.html