字符串类

String字符串类
①常用操作
1、获取字符串长度,字符串的长度是指其所包含的字符的个数。
str.length();
2、替换字符串(整体替换)
String str2 = str.replace("","");
3、字符串大小写转换
str.toLowerCase()/ str.toUpperCase()
4、删除字符串前后空格
str.trim();
5、字符串等值比较.
str.equals("");/equalsIgnoreCase("")-忽略大小写
6、字符串的开始/结尾是否与某个子串相同
boolean =str.startsWith("")/endsWith("")
7、搜索子串
int =indexOf("") //子字符串首次出现的位置。
lastIndexOf("") //搜索子字符串的最后一次出现的位置
8、子串截取
str.charAt(int)// 返回指定索引位置的字符
str.substring(int)// 返回指定索引开始的子串
str.substring(int,int)// 返回指定起始索引到结束索引之间的子串
9、字符串分解
String s = ",,,"; String sa[] = s.split(",")
10、字符串转字符数组
char c[] = str.toCharArray();
11、字符串转字节数组
byte b[] = str.getBytes();
12、将其他数据类型转换成字符串
str=String.valueOf(d);
13、把字符串转换成其它数据类型
转换为整型: Integer.parseInt(String s)
转换为长整型:Long.parseLong(String s)
转换为浮点型:Float.parseFloat(String s)
转换为双精型:Double.parseDouble(String s)
转换为逻辑型:Boolean.parseBoolean(String s)
②StringBuffer类--是一种可以改变(如增长、修改)的字符串对象,使用起来比String效率更高。
str.setLength(3);//设置字符串长度
str.append("");//追加数据
str.insert(int,"");//在指定位置插入子串
str.delete(2, 4);//删除从start开始到end-1结束的子字符串
str.deleteCharAt(4);//删除index处的字符
str2 = str.reverse();//字符串反转
str.setCharAt(2,'');//子串替换
str.replace(int,int,"");//从start至end-1处替换
str.toString();//类型转换


String:不可变字符串
StringBuffer:可变字符串(线程安全)

StringBuilder:可变字符串(非线程安全)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
设计 C++ 字符串类的主要考虑因素包括字符串的存储方式、操作方法、性能、安全等。 以下是一种可能的设计: ```c++ class MyString { public: MyString(); // 默认构造函数 MyString(const char* str); // 从 C-style 字符串构造 MyString(const MyString& other); // 拷贝构造函数 ~MyString(); // 析构函数 MyString& operator=(const MyString& other); // 拷贝赋值运算符 // 重载下标操作符 char& operator[](size_t index); const char& operator[](size_t index) const; // 获取字符串长度 size_t length() const; // 获取 C-style 字符串指针 const char* c_str() const; // 拼接字符串 MyString operator+(const MyString& other) const; MyString& operator+=(const MyString& other); // 比较字符串 bool operator==(const MyString& other) const; bool operator!=(const MyString& other) const; bool operator<(const MyString& other) const; bool operator>(const MyString& other) const; bool operator<=(const MyString& other) const; bool operator>=(const MyString& other) const; private: char* m_data; // 字符串数据存储 size_t m_length; // 字符串长度 }; ``` 其中,`m_data` 是字符串数据的存储,可以使用 `new` 运算符在堆上分配内存,需要在析构函数中使用 `delete[]` 释放内存。`m_length` 表示字符串的长度。 在构造函数和拷贝构造函数中,需要分配新的内存,并将传入的字符串复制到 `m_data` 中。在拷贝赋值运算符中,需要先释放 `m_data` 中的内存,再重新分配并复制传入的字符串。 重载下标操作符可以方便地获取字符串中的某个字符。 `length()` 可以返回字符串长度,`c_str()` 可以返回 C-style 字符串指针。 `operator+` 和 `operator+=` 可以进行字符串拼接操作。 比较操作符可以用于字符串的比较,包括相等性、大小关系等。 需要注意的是,在设计字符串类时,需要考虑到安全问题,避免出现缓冲区溢出等问题。因此,在实现字符串操作时需要对输入参数进行检查和验证。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值