Java程序员学习C++之字符串
2015-07-21 12:04
549 查看
#include <iostream> #include <string.h> using namespace std; int my_len(const char *str) { int len = 0; // while (*str != '\0') // { // ++len; // ++str; // } while (*(str++) != '\0') { ++len; } return len; } void my_cpy(char *dst,const char *src) { while (*src != '\0') { *dst = *src; ++dst; ++src; } } int main() { char str1[] = "abc";//后面自动加上'\0' char str2[] = { 'a', 'b', 'c' };//后面不会自动加上个'\0',作为字符串会一直找到'\0'标志 char str3[] = { 'a', 'b', 'c' ,'\0'}; char str4[10] = "abc"; // 4 3 4 10 cout << sizeof(str1) << "," << sizeof(str2) << "," << sizeof(str3) << "," << sizeof(str4) << endl; // 3 15 3 3 cout << strlen(str1) << "," << strlen(str2) << "," << strlen(str3) << "," << strlen(str4) << endl; cout << my_len(str1) << "," << my_len(str2) << "," << my_len(str3) << "," << my_len(str4) << endl; // abc abc烫烫烫烫蘟bc abc abc cout << str1 << "," << str2 << "," << str3 << "," << str4 << endl; //字符串赋值 //str1 = str2;// 错误,数组名是地址常量 //str1 = "hello";// 错误,数组名是地址常量 strcpy(str4,str1); //strcmp(str1,str2);字符串比较 //strcat(str3,str2);字符串拼接,必须判断空间是否够 //字符串分割 char str[] = "this is a test"; char *token = strtok(str, " "); while (token != NULL) { cout << token << endl; token = strtok(NULL," "); } return 0; }
c++风格字符串
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "hello";
string str2 = "abc";
string str3 = "abc";
//拷贝赋值
str3 = str1;
cout << str1 << "," << str3 << endl;
//获取长度
cout << str1.length() << endl;
//字符串的比较
str1.compare(str3);
//字符串拼接
str3 += str2;
//字符串分割
string str4 = "this is a test";
//转换为c风格的string
//char *token = strtok((char *)str4.c_str(), " ");//强制类型转换
char *token = strtok(const_cast<char *>(str4.c_str()), " ");
while (token != NULL)
{
cout << token << endl;
token = strtok(NULL, " ");
}
//遍历字符串(string::size_type i = 0; i < str1.length();i++)
for (string::size_type i = 0; i < str1.length(); i++)
{
cout << str1[i] << "-" ;
}
cout << endl;
for (string::size_type i = 0; i < str1.length(); i++)
{
cout << str1.at(i) << "-";
}
cout << endl;
for (string::iterator itr = str1.begin(); itr != str1.end();++itr)
{
cout << *itr << "-";
}
cout << endl;
int cnt = 0;
while (cnt < 50)
{
if (str1.size() == str1.capacity())
{
//cout << "hhh";
}
str1.push_back('*');
cnt++;
//cout << str1.size() << "," << str1.capacity() << endl;
}
str1.clear();
if (str1.empty())
{
cout << "str1.empty";
}
return 0;
}
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解