Strings in C and C++

本文详细介绍了C++中C字符串的使用方法,包括声明、初始化、赋值、连接、复制、比较长度、输出输入等操作,以及与C字符串的区别和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://cs.stmarys.ca/~porter/csc/ref/c_cpp_strings.html

This page summarizes many of the things you may find it    useful to know when working with either C-strings or objects of the C++   string class.

The term string generally means an ordered sequence of    characters, with a first character, a second character, and so on, and in    most programming languages such strings are enclosed in either single or    double quotes. In C++ the enclosing delimiters are double quotes. In this    form the string is referred to as a string literal and we often    use such string literals in output statements when we wish to display    text on the screen for the benefit of our users. For example, the usual    first C++ program displays the string literal "Hello, world!" on the    screen with the following output statement:

cout << "Hello, world!" << endl;

However, without string variables about all we can do with strings is    output string literals to the screen, so we need to expand our ability to    handle string data. When we talk about strings in C++, we must be careful    because the C language, with which C++ is meant to be backward    compatible, had one way of dealing with strings, while C++ has another,    and to further complicate matters there are many non-standard    implementations of C++ strings. These should gradually disappear as    compiler vendors update their products to implement the string component    of the C++ Standard Library.

As a programmer, then, you must distinguish between the following    three things:

  1. An "ordinary" array of characters, which is just like any other      array and has no special properties that other arrays do not have.
  2. A C-string, which consists of an array of characters terminated by      the null character '\0', and which therefore is different from an      ordinary array of characters. There is a whole library of functions for      dealing with strings represented in this form. Its header file is      <cstring>. In some implementations this library may be      automatically included when you include other libraries such as the     <iostream> library. Note that the null character may      very well not be the very last character in the C-string array, but it      will be the first character beyond the last character of the actual      string data in in that array. For example if you have a C-string      storing "Hello" in a character array of size 10, then the letters of      the word "Hello" will be in positions with indices 0 to 4, there will      be a null character at index 5, and the locations with indices 6 to 9      will contain who-knows-what. In any case, it's the null character at      index 5 that makes this otherwise ordinary character array a      C-string.
  3. A C++ string object, which is an instance of a "class" data type      whose actual internal representation you need not know or care about,      as long as you know what you can and can't do with variables (and      constants) having this data type. There is a library of C++ string      functions as well, available by including the <string>      header file.

Both the C-string library functions and the C++ string library    functions are available to C++ programs. But, don't forget that these are    two *different* function libraries, and the functions of the first    library have a different notion of what a string is from the    corresponding notion held by the functions of the second library. There    are two further complicating aspects to this situation: first, though a    function from one of the libraries may have a counterpart in the other    library (i.e., a function in the other library designed to perform the    same operation), the functions may not be used in the same way, and may    not even have the same name; second, because of backward compatibility    many functions from the C++ string library can be expected to work fine    and do the expected thing with C-style strings, but not the other way    around.

The last statement above might seem to suggest we should use C++    strings and forget about C-strings altogether, and it is certainly true    that there is a wider variety of more intuitive operations available for    C++ strings. However, C-strings are more primitive, you may therefore    find them simpler to deal with (provided you remember a few simple rules,    such as the fact that the null character must always terminate such    strings), and certainly if you read other, older programs you will see    lots of C-strings. So, use whichever you find more convenient, but if you    choose C++ strings and occasionally need to mix the two for some reason,    be extra careful. Finally, there are certain situations in which    C-stringsmust be used.

To understand strings, you will have to spend some time studying    sample programs. This study must include the usual prediction of how you    expect a program to behave for given input, followed by a compile, link    and run to test your prediction, as well as subsequent modification and    testing to investigate questions that will arise along the way. In    addition to experimenting with any supplied sample programs, you should    be prepared to make up your own.

In the following examples we attempt to draw the distinction between    the two string representations and their associated operations. The list    is not complete, but we do indicate how to perform many of the more    useful kinds of tasks with each kind of string. The left-hand column    contains examples relevant to C-strings and the right-hand column shows    analogous examples in the context of C++ strings.

C-strings  (#include <cstring>)         C++ strings  (#include <string>)
===============================         ================================
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!         !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Declaring a C-string variable           Declaring a C++ string object
-----------------------------           -----------------------------
char str[10];                           string str;

Initializing a C-string variable        Initializing a C++ string object
--------------------------------        --------------------------------
char str1[11] = "Call home!";           string str1("Call home!");
char str2[] = "Send money!";            string str2 = "Send money!";
char str3[] = {'O', 'K', '\0'};         string str3("OK");
Last line above has same effect as:
char str3[] = "OK";
                                        string str4(10, 'x');
                                        
Assigning to a C-string variable        Assigning to a C++ string object
--------------------------------        --------------------------------
Can't do it, i.e., can't do this:       string str;
char str[10];                           str = "Hello";
str = "Hello!";                         str = otherString;

Concatenating two C-strings             Concatenating two C++ string objects
---------------------------             ------------------------------------
strcat(str1, str2);                     str1 += str2;
strcpy(str, strcat(str1, str2));        str = str1 + str2;

Copying a C-string variable             Copying a C++ string object
---------------------------             ---------------------------
char str[20];                           string str;
strcpy(str, "Hello!");                  str = "Hello";
strcpy(str, otherString);               str = otherString;

Accessing a single character            Accessing a single character
----------------------------            ----------------------------
str[index]                              str[index]
                                        str.at(index)
                                        str(index, count)
                                        
Comparing two C-strings                 Comparing two C++ string objects
-----------------------                 --------------------------------
if (strcmp(str1, str2) < 0)             if (str1 < str2)
    cout << "str1 comes 1st.";              cout << "str1 comes 1st.";
if (strcmp(str1, str2) == 0)            if (str1 == str2)
    cout << "Equal strings.";               cout << "Equal strings.";
if (strcmp(str1, str2) > 0)             if (str1 > str2)
    cout << "str2 comes 1st.";              cout << "str2 comes 1st.";
    
Finding the length of a C-string        Finding the length of a C++ string object
--------------------------------        -----------------------------------------
strlen(str)                             str.length()

Output of a C-string variable           Output of a C++ string object
-----------------------------           -----------------------------
cout << str;                            cout << str;
cout << setw(width) << str;             cout << setw(width) << str;

In what follows, keep in mind that cin ignores white space when    reading a string, whilecin.get(), cin.getline() and     getline() do not. Remember too thatcin.getline() and     getline() consume the delimiter while cin.get() does not.    Finally, cin can be replaced with any open input stream, since file    input withinFile, say, behaves in a manner completely analogous to    the corresponding behavior ofcin. Analogously, in the output    examples given immediately above, cout could be replaced with any    text output stream variable, say outFile. In all cases,   numCh is the maximum number of characters that will be read.

Input of a C-style string variable         Input of a C++ string object
----------------------------------         ----------------------------
cin >> s;                                  cin >> s;
cin.get(s, numCh+1);
cin.get(s, numCh+1,'\n');
cin.get(s, numCh+1,'x');
cin.getline(s, numCh+1);                   getline(cin, s);
cin.getline(s, numCh+1, '\n');
cin.getline(s, numCh+1, 'x');              getline(cin, s, 'x');

A useful naming convention for C-strings is illustrated by examples    like

typedef char String80[81];
typedef char String20[21];

in which the two numbers in each definition differ by 1 to allow for    the null character '\0' to be stored in the array of characters, but to    *not* be considered as part of the string stored there. No analog to this    naming convention is necessary for C++ strings, since for all practical    purposes, each C++ string variable may contain a string value of    virtually unlimited length.

标题基于SpringBoot+Vue的学生交流互助平台研究AI更换标题第1章引言介绍学生交流互助平台的研究背景、意义、现状、方法与创新点。1.1研究背景与意义分析学生交流互助平台在当前教育环境下的需求及其重要性。1.2国内外研究现状综述国内外在学生交流互助平台方面的研究进展与实践应用。1.3研究方法与创新点概述本研究采用的方法论、技术路线及预期的创新成果。第2章相关理论阐述SpringBoot与Vue框架的理论基础及在学生交流互助平台中的应用。2.1SpringBoot框架概述介绍SpringBoot框架的核心思想、特点及优势。2.2Vue框架概述阐述Vue框架的基本原理、组件化开发思想及与前端的交互机制。2.3SpringBoot与Vue的整合应用探讨SpringBoot与Vue在学生交流互助平台中的整合方式及优势。第3章平台需求分析深入分析学生交流互助平台的功能需求、非功能需求及用户体验要求。3.1功能需求分析详细阐述平台的各项功能需求,如用户管理、信息交流、互助学习等。3.2非功能需求分析对平台的性能、安全性、可扩展性等非功能需求进行分析。3.3用户体验要求从用户角度出发,提出平台在易用性、美观性等方面的要求。第4章平台设计与实现具体描述学生交流互助平台的架构设计、功能实现及前后端交互细节。4.1平台架构设计给出平台的整体架构设计,包括前后端分离、微服务架构等思想的应用。4.2功能模块实现详细阐述各个功能模块的实现过程,如用户登录注册、信息发布与查看、在线交流等。4.3前后端交互细节介绍前后端数据交互的方式、接口设计及数据传输过程中的安全问题。第5章平台测试与优化对平台进行全面的测试,发现并解决潜在问题,同时进行优化以提高性能。5.1测试环境与方案介绍测试环境的搭建及所采用的测试方案,包括单元测试、集成测试等。5.2测试结果分析对测试结果进行详细分析,找出问题的根源并
内容概要:本文详细介绍了一个基于灰狼优化算法(GWO)优化的卷积双向长短期记忆神经网络(CNN-BiLSTM)融合注意力机制的多变量多步时间序列预测项目。该项目旨在解决传统时序预测方法难以捕捉非线性、复杂时序依赖关系的问题,通过融合CNN的空间特征提取、BiLSTM的时序建模能力及注意力机制的动态权重调节能力,实现对多变量多步时间序列的精准预测。项目不仅涵盖了数据预处理、模型构建与训练、性能评估,还包括了GUI界面的设计与实现。此外,文章还讨论了模型的部署、应用领域及其未来改进方向。 适合人群:具备一定编程基础,特别是对深度学习、时间序列预测及优化算法有一定了解的研发人员和数据科学家。 使用场景及目标:①用于智能电网负荷预测、金融市场多资产价格预测、环境气象多参数预报、智能制造设备状态监测与预测维护、交通流量预测与智慧交通管理、医疗健康多指标预测等领域;②提升多变量多步时间序列预测精度,优化资源调度和风险管控;③实现自动化超参数优化,降低人工调参成本,提高模型训练效率;④增强模型对复杂时序数据特征的学习能力,促进智能决策支持应用。 阅读建议:此资源不仅提供了详细的代码实现和模型架构解析,还深入探讨了模型优化和实际应用中的挑战与解决方案。因此,在学习过程中,建议结合理论与实践,逐步理解各个模块的功能和实现细节,并尝试在自己的项目中应用这些技术和方法。同时,注意数据预处理的重要性,合理设置模型参数与网络结构,控制多步预测误差传播,防范过拟合,规划计算资源与训练时间,关注模型的可解释性和透明度,以及持续更新与迭代模型,以适应数据分布的变化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值