[C++]cpp小笔记3 --- C++ String and char

原创 2013年12月05日 10:41:52

字符串实际上就是在内存中在连续位置上保存的字符,字符串结尾以'\0' null字符表示结束。

String在C++中有两种表现形式。1. 用C style; 2. 用String class.

1. C Style String

Store String in the form of an array of chars. The last bit of the char array MUST BE '\0' to indicate the end of the string.
char dog[8] = { 'b', 'e', 'a', 'u', 'x', ' ', 'I', 'I'}; // not a string!, continuous stored but not ended with '\0'
char cat[8] = {'f', 'a', 't', 'e', 's', 's', 'a', '\0'}; // a string!
char val[] = {"this is also a string"};                  //a string! '\0' is added implicitly for double quotation""
	cout <<sizeof(wchar_t) <<endl;
	cout<<sizeof(char32_t) <<endl;
	cout<<sizeof(char16_t) <<endl;
	wchar_t wchar[] = {L" a 4-Byte long string"};
	char32_t char32[] = {"a 4-Byte long string"};
	char16_t char16[] = {"a 2-Byte long string"};
Result is:

4

4

2



除了显式的指定'\0'的位置,还可以用"" 双引号来给char array初始化:
char bird[11] = "Mr. Cheeps";  // the \0 is understood
char fish[] = "Bubbles";   // let the compiler count

Quoted strings always include the terminating null character implicitly。要注意的一点是,正因为 " " 双引号会自动添加 \0, 所以"s"这样的一个字符实际上包含两个字符, 而's'近包含一个字符。
char shirt_size = 'S';   // this is fine
char shirt_size = ”S“;   // this is wrong

cin只能读取一个word, 任何空白符--space, tab, newline将结束cin读取,cin自动在读取的内容后添加'\0'并将内容保存在character array中。

例如:
#include <iostream>
#include "Chapter4.h"
using namespace std;

int main() {
	using namespace std;
	const int ArSize = 20;
	char name[ArSize];
	char dessert[ArSize];
	cout << "Enter your name:\n";
	cin >> name;
	cout << "Enter your favorite dessert:\n";
	cin >> dessert;
	cout << "I have some delicious " << dessert;
	cout << " for you, " << name << ".\n";
	return 0;
}

结果:
Enter your name:
Alistair Dreeb
Enter your favorite dessert:
I have some delicious Dreeb for you, Alistair.

2. C++ string class style string and its initialization

#include <string>

using namespace std;

string str1;
string str2 = "string";
string str3 = {"also a string"};
string str4 {"string too!"};

3. C-style and string style functions.

C-style
strcpy(dest, src);                                       //copy src char arry  to dest char array. 
strncpy(dest, src);                                     //copy "n" src char arry  to dest char array. 
strlen(chararray1);                                   //calulate the length of chars in chararray1
strcat(chararray1, chararray2);               //concate chararray2 to the end of chararray1

In C-style string, 
char char1[] = {'1','2','3'};
char char2[3];
char2 = char1;    //wrong, char copy need to use strcpy().


string ctyle functions:
string str = "xyz";
str.size();                          //size of str
#include <iostream>
#include "Chapter4.h"
#include <string>
#include <cstring>  //C-style string library
 using namespace std;

int main() {
	using namespace std;
	const int ArSize = 20;
	char name[ArSize] = "bbai";
	char dessert[ArSize];
	string namestr = "bbai";

	//strcpy name to dessert
	strcpy(dessert, name);
	cout <<" copy from " << name << " to "<<dessert<<endl;
	int n = 2;
	char dessert2[ArSize];

	//strncpy n characters from name to dessert2
	strncpy(dessert2, name, n);
	cout <<" copy first "<< n << "characters from " << name << " to "<<dessert2<<endl;

	//strcat
	strcat(dessert2, name);  //add name to the end of dessert2

	//strlen
	cout<< "length of name is " << strlen(name) << " length of dessert2 is " << strlen(dessert2) <<"  and lenght of string is " << namestr.size()<<endl;
	return 0;
}

Result:
 copy from bbai to bbai
 copy first 2characters from bbai to bb
length of name is 4 length of dessert2 is 6  and lenght of string is 4

Raw string representation. PS, tired with R but got error...

raw strings use "( and )" as delimiters, and they use anR prefix to identify them as rawstrings: 

cout << R"(Jim "King" Tutt uses "\n" instead of endl.)" << '\n';

This would display the following:

Jim "King" Tutt uses \n instead of endl.

The standard string literal equivalent would be this:

cout << "Jim \"King\" Tutt uses \" \\n\" instead of endl." << '\n'; 

cin.get(), cin.get(char) and cin>>ch

cin>>ch 会自动过滤whitespaces, new lines, and tabs, 所以一遇到这些字符就结束输入;

cin.get() & cin.get(char)不会过滤,会全部返回;

cin.get()读到EOF return false;
cin.get(char)读到EOFreturn EOF;



[C++]cpp小笔记3 --- C++基础类型的大小和转换

1. 类型的大小 A short integer is at least 16 bits wide.An int integer is at least as big as short.A ...

《C++ Primer第五版》读书笔记(3)--STRINGS, VECTORS AND ARRAYS

1      Strings, Vectors, and Arrays 1.1    Namespace using Declarations Headers Should NotInclude u...

Effective C++ (3rd Ed) 读书笔记(一)Item 2: Prefer constS, enumS, and inlineS to #defineS

#includecxvxv

c++ primer学习笔记3-标准库类型string&vector

1.string 与getline
  • wm_1991
  • wm_1991
  • 2014年11月05日 10:11
  • 360

C++ 温习笔记(3) - auto_ptr,string

auto_ptr 利用特点“栈上对象在离开作用范围时会自动析构”。 对于动态分配的内存,其作用范围是程序员手动控制的,这给程序员带来了方便但也不可避免疏忽造成的内存泄漏,毕竟只有编译器是最可靠的。 a...
  • zhxdick
  • zhxdick
  • 2016年05月18日 19:20
  • 734

C++ Primer学习笔记——$3 string类

题记:本系列学习笔记(C++ Primer学习笔记)主要目的是讨论一些容易被大家忽略或者容易形成错误认识的内容。只适合于有了一定的C++基础的读者(至少学完一本C++教程)。 作者: tyc611, ...
  • whycold
  • whycold
  • 2011年01月19日 14:33
  • 756

C/C++---C and CXX compiler with c or cpp in struct

C/C++中结构体初始化方法#include enum SIZE { SIZE_ONE = 1, SIZE_TWO = 2, SIZE_THREE = 3 };s...
  • FreeApe
  • FreeApe
  • 2017年01月05日 22:23
  • 429

关于C和C++中的基本数据类型int、long、long long、float、double、char、string的大小及表示范围

基本类型:int、short、long、char、bool、float、double、string的大小及范围的总结,及它们的符号类型详解。...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[C++]cpp小笔记3 --- C++ String and char
举报原因:
原因补充:

(最多只允许输入30个字)