C++字符串操作分析和总结.docxVIP

  • 3
  • 0
  • 约6.01千字
  • 约 20页
  • 2023-04-26 发布于上海
  • 举报
字符串操作是一个不小的主题,在标准 C++中,string 字符串类成为一个标准,之所以抛弃char*的字符串而选用 C++标准程序库中的 string 类,是因为他和前者比较起来,不必担心内存是否足够、字符串长度等等,而且作为一个类出现,他集成的操作函数足以完成我们大多数情况下的需要. 下面我们首先从一些示例开始学习下string 类的使用. 1) #include string #include iostream using namespace std; void main() { string s(hehe); string s1=abcd; couts” “s1endl; } 2) #include string #include iostream using namespace std; void main() { char chs[] = hehe; string s(chs); coutsendl; } 3) #include string #include iostream using namespace std; void main() { char chs[] = hehe; string s(chs,1,3); //指定从chs 的索引1 开始,最后复制3 个字节coutsendl; } 4) #include string #include iostream using namespace std; void main() { string s1(hehe); string s2(s1); couts2endl; } 5) #include string #include iostream using namespace std; void main() { string s1(hehe,2,3); string s2(s1); couts2endl; } 6) #include string #include iostream using namespace std; void main() { char chs[] = hehe; string s(chs,3); //将 chs 前 3 个字符作为初值构造coutsendl; } 7) #include string #include iostream using namespace std; void main() { string s(10,k); //分配 10 个字符,初值都是k coutsendl; } //以上是 string 类实例的构造手段,都很简单. 9) // 赋 新 值 #include string #include iostream using namespace std; void main() { string s(10,k); //分配 10 个字符,初值都是k coutsendl; s = hehehehe; coutsendl; s.assign(kdje); coutsendl; s.assign(fkdhfkdfd,5); //重新分配指定字符串的前 5 的元素内 容 coutsendl; } 10) //swap 方法交换#include string #include iostream using namespace std; void main() { string s1 = hehe; string s2 = gagaga; couts1 : s1endl; couts2 : s2endl; s1.swap(s2); couts1 : s1endl; couts2 : s2endl; } 11) //+=,append(),push_back()在尾部添加字符#include string #include iostream using namespace std; void main() { string s = hehe; s += gaga; coutsendl; s.append(嘿嘿); //append()方法可以添加字符串coutsendl; s.push_back(k); //push_back()方法只能添加一个字符... coutsendl; } 12) //insert() 插入字符.其实,insert 运用好,与其他的插入操作是一样的. #include string #include iostream using namespace std; void main() { string s = hehe; s.insert(0,头部); //在头部插入s.insert(s.size(),尾部); //在尾部插入 s.insert(s.size()/2,中间);//在中间插入c

文档评论(0)

1亿VIP精品文档

相关文档