Java程序猿学习C++之字符串
Posted Brenda
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java程序猿学习C++之字符串相关的知识,希望对你有一定的参考价值。
#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; }
以上是关于Java程序猿学习C++之字符串的主要内容,如果未能解决你的问题,请参考以下文章
黑马程序猿 ---------- Java网络技术之 ---正則表達式 (Day06)
《Java程序猿面试笔试宝典》之字符串创建与存储的机制是什么
疯狂Java学习笔记(70)-----------挚爱Java