c++中string的用法
- 格式:doc
- 大小:64.00 KB
- 文档页数:6
c++中strstr的用法在C语言中,strstr是一个非常有用的函数,它用于在一个字符串中查找另一个字符串的出现位置。
通过使用strstr函数,我们可以轻松地查找文本中的特定模式,这对于字符串处理和数据解析等任务非常有用。
本文将介绍strstr函数的用法,并分析其在实际应用中的优势和注意事项。
一、strstr函数的定义和用法strstr函数是C语言标准库中的一个函数,它接受两个字符串参数,并返回一个指向第一个匹配位置的指针。
如果找不到匹配的字符串,则返回NULL。
使用strstr函数的基本语法如下:```cchar*strstr(constchar*haystack,constchar*needle);```其中,haystack是要搜索的字符串,needle是要查找的模式字符串。
strstr 函数会在haystack中查找needle的出现位置,并返回一个指向匹配位置的指针。
二、使用strstr函数的示例下面是一个使用strstr函数的简单示例,演示了如何在一个字符串中查找另一个字符串的出现位置:```c#include<stdio.h>#include<string.h>intmain(){charstr1[100]="Hello,world!Thisisateststring.";charstr2[]="world";intpos=strstr(str1,str2);if(pos!=NULL){printf("Found'%s'atposition%d.\n",str2,pos);}else{printf("'%s'notfound.\n",str2);}return0;}```输出结果为:`Found'world'atposition16.`,表示在字符串"Hello,world!Thisisateststring."中找到了"world"的出现位置为16。
c_str函数c_str()函数是C++ STL(Standard Template Library)库中的一个函数,它主要用于将字符串类型的字符数组(包括C++字符串和C字符数组)转换为C类型字符串,即以'\0'结尾的字符数组。
在这篇文章中,我们将详细介绍c_str()函数及其用途、使用方法和注意事项。
c_str()函数的主要用途是将C++的string类型转换为C风格的字符串类型,也就是将string类型的字符串转换为const char类型的字符串,便于和C语言中的函数交互和传递参数。
C++中的string类型和C语言中的字符串类型的最大区别是,string类型是一个类,而C语言中的字符串类型只是一个字符序列,以'\0'结尾。
而C++中的string类型默认不以'\0'结尾,所以它不能像C语言中的字符串那样直接传递给C语言库函数使用。
为了解决这个问题,我们必须使用c_str()函数将string类型转换为C风格的字符串类型。
c_str()函数的用法非常简单,只需要在string变量后添加.c_str()即可。
例如:```C++std::string str = "Hello, world!";const char* cstr = str.c_str();```在这个例子中,我们先定义了一个string类型的变量str,并将其初始化为“Hello, world!”字符串。
然后,我们使用c_str()函数将str转换为C风格的字符串类型,并将结果保存在一个const char指针变量cstr中。
1. 返回值是const char*类型c_str()函数的返回类型是const char *类型,也就是指向一段以'\0'结尾的字符数组的指针。
由于返回的指针是指向string对象内部的字符数组,因此不能修改该指针指向的内容。
c语言中标记的用法在C语言中,标记(Token)是语言中的一个基本单位,它是语言中的一个词或字符的序列。
标记可以分为以下几种类型:1. 标识符(Identifier):标识符是用来表示变量、函数、结构体等实体的名称。
标识符必须以字母、下划线或汉字开头,后面可以是字母、数字、下划线或汉字的组合。
例如:int、printf、x、_count等。
2. 关键字(Keyword):关键字是C语言中具有特殊含义的词汇。
这些词汇被C语言保留,不能用作用户自定义的标识符。
例如:int、char、for、if等。
3. 运算符(Operator):运算符是用来进行各种运算操作的符号。
例如:+、-、*、/、>、<等。
4. 分隔符(Delimiter):分隔符用于标识程序中不同的结构和语句的开始和结束。
例如:{}、()、[]、,、;等。
5. 常量(Constant):常量是程序中固定不变的数据值。
常量可以分为整型常量、浮点型常量、字符常量和字符串常量等。
6. 字符串(String):字符串是由一串字符组成的序列。
字符串常量用双引号括起来。
例如:"Hello, World!"。
7. 注释(Comment):注释是程序中的一种文本,用于对程序进行解释和说明。
注释不会被编译,只是起辅助作用。
注释可以使用//或/*...*/表示。
在C语言中,编译器会将源代码分解成一个个标记,并根据标记的类型进行相应的处理。
标记在程序分析、词法分析和语法分析等过程中起到了重要的作用。
在 C 语言中,字符串(String)实际上是一个字符数组,以 null 字符('\0')结尾。
C 中没有专门的字符串类型,而是使用字符数组来表示字符串。
以下是一些常见的C 中字符串的用法:
字符数组声明和初始化:
字符串输入和输出:
字符串函数:
C 标准库提供了许多用于处理字符串的函数,这些函数定义在string.h头文件中。
以下是一些常见的字符串函数:
•strlen:计算字符串的长度。
•strcpy 和 strncpy:复制字符串。
•strcat 和 strncat:连接字符串。
这只是 C 语言中字符串的基础用法。
需要注意的是,C 中的字符串是以 null 字符结尾的字符数组,因此在操作字符串时需要确保数组足够大以容纳字符串及其 null 字符。
此外,使用字符串函数时要注意数组边界,以防止缓冲区溢出。
转:std::string用法详解前言: string 的角色1 string 使用1.1 充分使用string 操作符1.2 眼花缭乱的string find 函数1.3 string insert, replace, erase 2 string 和 C风格字符串3 string 和 Charactor Traits4 string 建议5 附录前言: string 的角色1、 string 使用其实,string并不是一个单独的容器,只是basic_string 模板类的一个typedef 而已,相对应的还有wstring, 你在string 头文件中你会发现下面的代码:extern "C++" {typedef basic_string <char> string;typedef basic_string <wchar_t> wstring;} // extern "C++"由于只是解释string的用法,如果没有特殊的说明,本文并不区分string 和 basic_string的区别。
string 其实相当于一个保存字符的序列容器,因此除了有字符串的一些常用操作以外,还有包含了所有的序列容器的操作。
字符串的常用操作包括:增加、删除、修改、查找比较、链接、输入、输出等。
详细函数列表参看附录。
不要害怕这么多函数,其实有许多是序列容器带有的,平时不一定用的上。
如果你要想了解所有函数的详细用法,你需要查看basic_string,或者下载STL编程手册。
这里通过实例介绍一些常用函数。
1.1 充分使用string 操作符string 重载了许多操作符,包括 +, +=, <, =, , [], <<, >>等,正式这些操作符,对字符串操作非常方便。
先看看下面这个例子:tt.cpp(例程2)#i nclude <string>#i nclude <iostream>using namespace std;int main(){string strinfo="Please input your name:";cout << strinfo ;cin >> strinfo;if( strinfo == "winter" )cout << "you are winter!"<<endl;else if( strinfo != "wende" )cout << "you are not wende!"<<endl;else if( strinfo < "winter")cout << "your name should be ahead of winter"<<endl;elsecout << "your name should be after of winter"<<endl;strinfo += " , Welcome to China!";cout << strinfo<<endl;cout <<"Your name is :"<<endl;string strtmp = "How are you? " + strinfo;for(int i = 0 ; i < strtmp.size(); i ++)cout<<strtmp[i];return 0;}下面是程序的输出-bash-2.05b$ make ttc++ -O -pipe -march=pentiumpro tt.cpp -o tt-bash-2.05b$ ./ttPlease input your name:Heroyou are not wende!Hero , Welcome to China!How are you? Hero , Welcome to China!有了这些操作符,在STL中仿函数都可以直接使用string作为参数,例如 less, great, equal_to 等,因此在把string作为参数传递的时候,它的使用和int 或者float等已经没有什么区别了。
VC++标准C++中的string类的⽤法总结相信使⽤过MFC编程的朋友对CString这个类的印象应该⾮常深刻吧?的确,MFC中的CString类使⽤起来真的⾮常的⽅便好⽤。
但是如果离开了MFC框架,还有没有这样使⽤起来⾮常⽅便的类呢?答案是肯定的。
也许有⼈会说,即使不⽤MFC框架,也可以想办法使⽤MFC中的API,具体的操作⽅法在本⽂最后给出操作⽅法。
其实,可能很多⼈很可能会忽略掉标准C++中string类的使⽤。
标准C++中提供的string类得功能也是⾮常强⼤的,⼀般都能满⾜我们开发项⽬时使⽤。
现将具体⽤法的⼀部分罗列如下,只起⼀个抛砖引⽟的作⽤吧,好了,废话少说,直接进⼊正题吧!要想使⽤标准C++中string类,必须要包含#include <string>// 注意是<string>,不是<string.h>,带.h的是C语⾔中的头⽂件using std::string;using std::wstring;或using namespace std;下⾯你就可以使⽤string/wstring了,它们两分别对应着char和wchar_t。
string和wstring的⽤法是⼀样的,以下只⽤string作介绍:string类的构造函数:string(const char *s);//⽤c字符串s初始化<BR>string(int n,char c);//⽤n个字符c初始化此外,string类还⽀持默认构造函数和复制构造函数,如string s1;string s2="hello";都是正确的写法。
当构造的string太长⽽⽆法表达时会抛出length_error异常;string类的字符操作:const char &operator[](int n)const;const char &at(int n)const;char &operator[](int n);char &at(int n);//operator[]和at()均返回当前字符串中第n个字符的位置,但at函数提供范围检查,当越界时会抛出out_of_range异常,下标运算符[]不提供检查访问。
C#中string.format⽤法详解String.Format ⽅法的⼏种定义:String.Format (String, Object) 将指定的 String 中的格式项替换为指定的 Object 实例的值的⽂本等效项。
String.Format (String, Object[]) 将指定 String 中的格式项替换为指定数组中相应 Object 实例的值的⽂本等效项。
String.Format (IFormatProvider, String, Object[]) 将指定 String 中的格式项替换为指定数组中相应 Object 实例的值的⽂本等效项。
指定的参数提供区域性特定的格式设置信息。
String.Format (String, Object, Object) 将指定的 String 中的格式项替换为两个指定的 Object 实例的值的⽂本等效项。
String.Format (String, Object, Object, Object) 将指定的 String 中的格式项替换为三个指定的 Object 实例的值的⽂本等效项。
常⽤的格式化数值结果表字符说明⽰例输出C货币string.Format("{0:C3}", 2)$2.000D⼗进制string.Format("{0:D3}", 2)002E科学计数法 1.20E+001 1.20E+001G常规string.Format("{0:G}", 2)2N⽤分号隔开的数字string.Format("{0:N}", 250000)250,000.00X⼗六进制string.Format("{0:X000}", 12)Cstring.Format("{0:000.000}", 12.2)012.200常⽤的⼏种实例1、字符串的数字格式代码如下:string str1 =string.Format("{0:N1}",56789); //result: 56,789.0string str2 =string.Format("{0:N2}",56789); //result: 56,789.00string str3 =string.Format("{0:N3}",56789); //result: 56,789.000string str8 =string.Format("{0:F1}",56789); //result: 56789.0string str9 =string.Format("{0:F2}",56789); //result: 56789.00string str11 =(56789 / 100.0).ToString("#.##"); //result: 567.89string str12 =(56789 / 100).ToString("#.##"); //result: 567string str = string.Format("{0:f2}", .2); //result: 0.202、格式化货币(跟系统的环境有关,中⽂系统默认格式化⼈民币,英⽂系统格式化美元)代码如下:string.Format("{0:C}",0.2)结果为:¥0.20 (英⽂操作系统结果:$0.20)默认格式化⼩数点后⾯保留两位⼩数,如果需要保留⼀位或者更多,可以指定位数代码如下:string.Format("{0:C1}",23.15)结果为:¥23.2 (截取会⾃动四舍五⼊)格式化多个Object实例代码如下:string.Format("市场价:{0:C},优惠价{1:C}",23.15,19.82)3、格式化⼗进制的数字(格式化成固定的位数,位数不能少于未格式化前,只⽀持整形)代码如下:string.Format("{0:D3}",23) //结果为:023string.Format("{0:D2}",1223) //结果为:1223,(精度说明符指⽰结果字符串中所需的最少数字个数。
strlwr在c语言中的用法**The Usage of `strlwr` in C Language****I. Basic Usage**In C, the `strlwr` function is used to convert a string to lowercase. It takes a string as its argument and modifies the original string by converting all the uppercase characters in it to lowercase. For example:1. “I have a string `HELLO`. When I use `strlwr` on it, it becomes `hello`.”- In C code, it would be like this:```c#include <stdio.h>#include <string.h>int main() {char str[] = "HELLO";strlwr(str);printf("%s\n", str);return 0;```- Here, we can see that the function directly acts on the given string and changes its case. It's like a magic wand that transforms the uppercase letters into lowercase ones.2. “You know, if you have a string variable `MyString` with some uppercase characters, `strlwr` is the function that can make it all lowercase.”- Let's say `MyString` is defined as `char MyString[] = "This Is A TEST";````c#include <stdio.h>#include <string.h>int main() {char MyString[] = "This Is A TEST";strlwr(MyString);printf("%s\n", MyString);return 0;}- Oh, look! The string now looks so different, just like a person changing from a formal dress to a casual one.3. “He has a program where he needs to standardize all the input strings to lowercase. `strlwr` is his go - to function.”- Suppose he gets user input like `USER INPUT`.```c#include <stdio.h>#include <string.h>int main() {char input[100];scanf("%s", input);strlwr(input);printf("The standardized input is: %s\n", input);return 0;}```- This makes the input more uniform, much like putting allthe toys in a box in the same orientation.4. “She was so happy when she found out that `strlwr` can solve her problem of inconsistent string cases.”- Her strings were all over the place with different cases, like a messy room.```c#include <stdio.h>#include <string.h>int main() {char strs[][100] = {"AbC", "dEf", "Ghi"};int i;for (i = 0; i < 3; i++) {strlwr(strs[i]);printf("%s ", strs[i]);}return 0;}```- Now her strings are all neat and in lowercase, just like a well - organized bookshelf.5. “They thought it would be a complex task to convert all the strings in their project to lowercase, but `strlwr` made it a p iece of cake.”- In their project, they had an array of strings.```c#include <stdio.h>#include <string.h>int main() {char *strings[] = {"HeLLo", "WORLD", "How are you"};int num_strings = sizeof(strings) / sizeof(strings[0]);int j;for (j = 0; j < num_strings; j++) {strlwr(strings[j]);printf("%s ", strings[j]);}return 0;}```- It's amazing how such a simple function can do so much, isn't it?**II. Fixed Combinations (not really many in the case of `strlwr` but still relevant scenarios)**1. “When combined with `strcpy`, you can first convert a string to lowercase using `strlwr` and then copy it to another variable. It's like a two - step process of making a clone but in a different form.”- Consider this code:```c#include <stdio.h>#include <string.h>int main() {char original[] = "UPPERCASE STRING";char copy[100];strlwr(original);strcpy(copy, original);printf("The copied and lowercased string is: %s\n", copy);return 0;}```- Here, we first transform the original string and then create a copy of it. It's as if we are painting a picture in one color and then making a copy of that painted picture.2. “If you use `strlwr` along with a loop to process an array of strings, it's like a conveyor belt that takes each string and makes it lowercase one by one.”- For example:```c#include <stdio.h>#include <string.h>int main() {char string_array[][100] = {"HI", "THERE", "EVERYONE"};int size = sizeof(string_array) / sizeof(string_array[0]);int k;for (k = 0; k < size; k++) {strlwr(string_array[k]);printf("%s ", string_array[k]);}return 0;}```- Each string in the array is being processed just like items on a conveyor belt in a factory.3. “You can also use `strlwr` in combin ation with a function that checks for string equality. Imagine you have two strings, one in uppercase and one in lowercase. First, use `strlwr` on the uppercase one and then check if they are equal. It's like leveling the playing field before a comparison.”- The code could be:```c#include <stdio.h>#include <string.h>int main() {char str1[] = "ABC";char str2[] = "abc";strlwr(str1);if (strcmp(str1, str2) == 0) {printf("The strings are equal after making the first one lowercase.\n");} else {printf("The strings are not equal.\n");}return 0;}```- This is a useful way to make sure our comparison is fair, don't you think?4. “When using `strlwr` with a file - reading operation, you can standardize all the strings read from the file to lowercase. It's like putting all the words from a book into a single case, making it easier to analyze.”- Here's a simple example:```c#include <stdio.h>#include <string.h>int main() {FILE *fp;char buffer[100];fp = fopen("test.txt", "r");if (fp!= NULL) {while (fgets(buffer, 100, fp)!= NULL) { buffer[strcspn(buffer, "\n")] = '\0'; strlwr(buffer);printf("%s\n", buffer);}fclose(fp);}return 0;}```- Now all the strings from the file are in lowercase, which can be really helpful in many text - processing tasks.5. “If you combine `strlwr` with a function that counts the occurrences of a character in a string, it can be easier to count because all the cases are the same. It's like having all the apples in one bas ket instead of some in one and some in another.”- Let's assume we have a function `count_char` that counts the occurrences of a character in a string.```c#include <stdio.h>#include <string.h>int count_char(char *str, char c) {int count = 0;int i;for (i = 0; str[i]!= '\0'; i++) {if (str[i] == c) {count++;}}return count;}int main() {char str[] = "Hello, World";strlwr(str);int num_a = count_char(str, 'l');printf("The number of 'l' in the lowercased stringis: %d\n", num_a);return 0;}```- This combination can make our string - processing tasks more straightforward.。
Cstring和string的区别和联系相同点:(1)用他们都可以取代对char*的使用。
(2)都封装了有丰富的字符串操作接口。
(3)他们都是C++的类库。
--以string的使用为例,不能有如下用法:string * pstr = NULL; //定义一个指向字符串的指针pstr->append("Hello world."); //在该字符串的末尾粘接上另一个字符。
这样做编译器不会有任何警告和错误,但是运行的时候就会有异常。
原因是没有理解string是一个类,而在定义类的对象的时候是需要调用其构造函数的。
上面既没有调用string的构造函数,而且还把指针赋值为NULL,很明显调用该类的对象的接口的时候会出错。
但是编译器却发现不了这个问题的。
正确的方法是如下:/*这里必须要用c++的宏new,而不能用c中的malloc,原因是new不但会分配一块内存,*//*还执行了类的构造函数。
当然,string类的实例化还可以通过已有的某个string对象进行,请另查阅*/string * pstr = new string("Hello world.");pstr->append("Hello world.");cout<<"string * pstr is:"<<*pstr<<endl;或者不用指针,如下也可以:string str; //会自动调用默认的构造函数,构造一个string类的对象。
str.apend("Hello world.");cout<<"string str is:"<<str<<endl;(4)他们都使用了模板的技术。
不同之处:(1)CString 类是微软的visual c++提供的MFC里面的一个类,所以只有支持MFC的工程才可以使用。
strlen的用法strlen函数(stringlength)是C语言中常用的一种函数,它可以查找字符串的长度,也就是字符串可以包含的字符数量,而不是字符数组的长度。
strlen函数的语法如下:strlen(string);其中string是要检测的字符串,strlen函数返回string中字符的个数,不包括结束符0,返回值为整数。
strlen函数的一般使用方法是:首先,在程序中引用头文件string.h,这是要使用strlen函数所必须引入的头文件;其次,使用strlen函数检查字符串的长度,表达式为:strlen(string),其中string是要检测的字符串;最后,拿到strlen函数的返回值,通常是表示字符串长度的整数,在程序中进行后续处理。
使用实例:#include<stdio.h>#include<string.h>int main(){char a[100]=helloint b=0;b=strlen(a);printf(字符串a的长度是:%db);return 0;}编译运行结果如下:字符串a的长度是:5以上是strlen函数的一般使用案例,由于strlen函数只能计算低位字符串的长度,因此不能用于计算单字节字符串的长度,也不能使用于计算宽字节字符串的长度。
除了strlen函数,还有其他一些函数可以用于计算字符串的长度,例如wcscspn函数、_mbslen函数、wcslen函数和_mbstrlen函数等。
wcscspn函数是返回一个字符数组中的字符的宽字节数,而_mbslen函数是返回宽字节字符串的长度,wcslen函数是返回宽字节字符串的长度,而_mbstrlen函数是返回多字节字符串的字节数,而strlen函数是返回低位字符串的长度。
因此,当要求在C语言编程中检测字符串长度时,可以根据字符串的不同类型,选择合适的函数来使用。
由于strlen函数只能计算低位字符串的长度,因此在使用时也要注意不要传入宽字节字符串,因为这样会导致检测结果不正确,可能会导致后续处理出现错误,因此使用时一定要注意。
c++中string的用法浏览次数:15635次悬赏分:10 |解决时间:2007-12-15 09:22 |提问者:zys860418string在c++中是作什么用的阿?既有string str声明变量的,也有string(n,' ')的,我是新手,谢谢了。
最佳答案之所以抛弃char*的字符串而选用C++标准程序库中的string类,是因为他和前者比较起来,不必担心内存是否足够、字符串长度等等,而且作为一个类出现,他集成的操作函数足以完成我们大多数情况下(甚至是100%)的需要。
我们可以用= 进行赋值操作,== 进行比较,+ 做串联(是不是很简单?)。
我们尽可以把它看成是C++的基本数据类型。
首先,为了在我们的程序中使用string类型,我们必须包含头文件<string>。
如下:#include <string> //注意这里不是string.h string.h是C字符串头文件1.声明一个C++字符串声明一个字符串变量很简单:string Str;这样我们就声明了一个字符串变量,但既然是一个类,就有构造函数和析构函数。
上面的声明没有传入参数,所以就直接使用了string的默认的构造函数,这个函数所作的就是把Str初始化为一个空字符串。
String类的构造函数和析构函数如下:a) string s; //生成一个空字符串sb) string s(str) //拷贝构造函数生成str的复制品c) string s(str,stridx) //将字符串str内"始于位置stridx"的部分当作字符串的初值d) string s(str,stridx,strlen) //将字符串str内"始于stridx且长度顶多strlen"的部分作为字符串的初值e) string s(cstr) //将C字符串作为s的初值f) string s(chars,chars_len) //将C字符串前chars_len个字符作为字符串s的初值。
g) string s(num,c) //生成一个字符串,包含num个c字符h) string s(beg,end) //以区间beg;end(不包含end)内的字符作为字符串s 的初值i) s.~string() //销毁所有字符,释放内存都很简单,我就不解释了。
2.字符串操作函数这里是C++字符串的重点,我先把各种操作函数罗列出来,不喜欢把所有函数都看完的人可以在这里找自己喜欢的函数,再到后面看他的详细解释。
a) =,assign() //赋以新值b) swap() //交换两个字符串的内容c) +=,append(),push_back() //在尾部添加字符d) insert() //插入字符e) erase() //删除字符f) clear() //删除全部字符g) replace() //替换字符h) + //串联字符串i) ==,!=,<,<=,>,>=,compare() //比较字符串j) size(),length() //返回字符数量k) max_size() //返回字符的可能最大个数l) empty() //判断字符串是否为空m) capacity() //返回重新分配之前的字符容量n) reserve() //保留一定量内存以容纳一定数量的字符o) [ ], at() //存取单一字符p) >>,getline() //从stream读取某值q) << //将谋值写入streamr) copy() //将某值赋值为一个C_strings) c_str() //将内容以C_string返回t) data() //将内容以字符数组形式返回u) substr() //返回某个子字符串v)查找函数w)begin() end() //提供类似STL的迭代器支持x) rbegin() rend() //逆向迭代器y) get_allocator() //返回配置器下面详细介绍:2.1 C++字符串和C字符串的转换C ++提供的由C++字符串得到对应的C_string的方法是使用data()、c_str()和copy(),其中,data()以字符数组的形式返回字符串内容,但并不添加’\0’。
c_str()返回一个以‘\0’结尾的字符数组,而copy()则把字符串的内容复制或写入既有的c_string或字符数组内。
C++字符串并不以’\0’结尾。
我的建议是在程序中能使用C++字符串就使用,除非万不得已不选用c_string。
由于只是简单介绍,详细介绍掠过,谁想进一步了解使用中的注意事项可以给我留言(到我的收件箱)。
我详细解释。
2.2 大小和容量函数一个C++字符串存在三种大小:a)现有的字符数,函数是size()和length(),他们等效。
Empty()用来检查字符串是否为空。
b)max_size() 这个大小是指当前C++字符串最多能包含的字符数,很可能和机器本身的限制或者字符串所在位置连续内存的大小有关系。
我们一般情况下不用关心他,应该大小足够我们用的。
但是不够用的话,会抛出length_error异常c)capacity()重新分配内存之前string所能包含的最大字符数。
这里另一个需要指出的是reserve()函数,这个函数为string重新分配内存。
重新分配的大小由其参数决定,默认参数为0,这时候会对string进行非强制性缩减。
还有必要再重复一下C++字符串和C字符串转换的问题,许多人会遇到这样的问题,自己做的程序要调用别人的函数、类什么的(比如数据库连接函数Connect(char*,char*)),但别人的函数参数用的是char*形式的,而我们知道,c_str()、data()返回的字符数组由该字符串拥有,所以是一种const char*,要想作为上面提及的函数的参数,还必须拷贝到一个char*,而我们的原则是能不使用C 字符串就不使用。
那么,这时候我们的处理方式是:如果此函数对参数(也就是char*)的内容不修改的话,我们可以这样Connect((char*)UserID.c_str(), (char*)PassWD.c_str()),但是这时候是存在危险的,因为这样转换后的字符串其实是可以修改的(有兴趣地可以自己试一试),所以我强调除非函数调用的时候不对参数进行修改,否则必须拷贝到一个char*上去。
当然,更稳妥的办法是无论什么情况都拷贝到一个char*上去。
同时我们也祈祷现在仍然使用C字符串进行编程的高手们(说他们是高手一点儿也不为过,也许在我们还穿开裆裤的时候他们就开始编程了,哈哈…)写的函数都比较规范,那样我们就不必进行强制转换了。
2.3元素存取我们可以使用下标操作符[]和函数at()对元素包含的字符进行访问。
但是应该注意的是操作符[]并不检查索引是否有效(有效索引0~str.length()),如果索引失效,会引起未定义的行为。
而at()会检查,如果使用at()的时候索引无效,会抛出out_of_range异常。
有一个例外不得不说,const string a;的操作符[]对索引值是a.length()仍然有效,其返回值是’\0’。
其他的各种情况,a.length()索引都是无效的。
举例如下:const string Cstr("const string");string Str("string");Str[3]; //okStr.at(3); //okStr[100]; //未定义的行为Str.at(100); //throw out_of_rangeStr[Str.length()] //未定义行为Cstr[Cstr.length()] //返回‘\0’Str.at(Str.length());//throw out_of_rangeCstr.at(Cstr.length()) ////throw out_of_range我不赞成类似于下面的引用或指针赋值:char& r=s[2];char* p= &s[3];因为一旦发生重新分配,r,p立即失效。
避免的方法就是不使用。
2.4比较函数C ++字符串支持常见的比较操作符(>,>=,<,<=,==,!=),甚至支持string 与C-string的比较(如str<"hello")。
在使用>,>=,<,<=这些操作符的时候是根据"当前字符特性"将字符按字典顺序进行逐一得比较。
字典排序靠前的字符小,比较的顺序是从前向后比较,遇到不相等的字符就按这个位置上的两个字符的比较结果确定两个字符串的大小。
同时,string ("aaaa") <string(aaaaa)。
另一个功能强大的比较函数是成员函数compare()。
他支持多参数处理,支持用索引值和长度定位子串来进行比较。
他返回一个整数来表示比较结果,返回值意义如下:0-相等〉0-大于<0-小于。
举例如下:string s("abcd");pare("abcd"); //返回0pare("dcba"); //返回一个小于0的值pare("ab"); //返回大于0的值pare(s); //相等pare(0,2,s,2,2); //用"ab"和"cd"进行比较小于零pare(1,2,"bcx",2); //用"bc"和"bc"比较。
怎么样?功能够全的吧!什么?还不能满足你的胃口?好吧,那等着,后面有更个性化的比较算法。
先给个提示,使用的是STL的比较算法。
什么?对STL一窍不通?靠,你重修吧!2.5 更改内容这在字符串的操作中占了很大一部分。
首先讲赋值,第一个赋值方法当然是使用操作符=,新值可以是string(如:s=ns) 、c_string(如:s="gaint")甚至单一字符(如:s=’j’)。
还可以使用成员函数assign(),这个成员函数可以使你更灵活的对字符串赋值。
还是举例说明吧:s.assign(str); //不说s.assign(str,1,3);//如果str是"iamangel" 就是把"ama"赋给字符串s.assign(str,2,string::npos);//把字符串str从索引值2开始到结尾赋给ss.assign("gaint"); //不说s.assign("nico",5);//把’n’ ‘I’ ‘c’ ‘o’ ‘\0’赋给字符串s.assign(5,’x’);//把五个x赋给字符串把字符串清空的方法有三个:s="";s.clear();s.erase();(我越来越觉得举例比说话让别人容易懂!)。