您的位置:首页 > 编程语言 > C语言/C++

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++