一、C length函数头文件
C++的 string 类是 C++ 标准中用于处理字符串的最主要的类之一。C++ 的 string类 中包含了许多方便的函数,以帮助我们方便地进行字符串的处理。其中,length() 函数是 string 类中的一个重要函数。
在使用 length() 函数时,我们需要引入头文件 string.h 或者 cstring。通过这些头文件,我们可以使用字符串处理函数库中定义的函数,如 strlen()、strcpy()、strcat()、strcmp() 等。
二、C length函数用法
C++ 标准库中的 string 类对象可以通过使用 length() 函数来计算字符串的长度。
#include
#include
using namespace std;
int main()
{
string str1 = "Hello, World!";
cout << "Length of string is : " << str1.length();
cout << endl;
return 0;
}
运行上面的代码,我们可以得到以下输出:
Length of string is : 13
这里,我们定义了一个 string 类型的变量 str1,并将其初始化为 “Hello, World!”。然后,我们利用 length() 函数计算了该字符串的长度。输出结果为 13,与该字符串的长度相等。
三、C length函数d, clength函数, c length函数 数组的长度
C++ 中还有其他函数可以用于计算字符串的长度。
在 C 语言中,strlen() 函数是计算字符串长度的标准函数,并且其返回值的类型为 size_t。它在头文件 string.h 或 cstring 中被声明。C++ 中的 length() 函数与 strlen() 函数不同,前者是 string 类下的函数,后者是 C 语言中的函数。
#include
#include
using namespace std;
int main()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* 复制 str1 到 str3 */
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
/* 连接 str1 和 str2 */
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
/* 连接后,str1 的总长度 */
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
return 0;
}
上述代码中,我们定义了三个 char 类型的字符串,并且使用了 strcpy() 和 strcat() 函数将它们复制和连接。然后,我们用 strlen() 函数分别计算了 str1 与 str2 相连后的字符串长度。
四、C函数 int, 函数len
除了 string 类和 C 语言中的函数,C++ 标准库还提供了一些其他的函数,可以用于计算字符串长度。
比如,我们可以使用 cctype 头文件中的函数 int ispunct ( int c ) 来计算一个字符串中的标点符号数,并用字符串总长度减去标点符号数,就可以得到字符串中字符数。
#include
#include
#include // 包含cctype头文件用于计算标点符号
using namespace std;
int main()
{
string str = "hello 123 ., world?";
int length = str.length();
int punct_count = 0;
for (int i = 0; i < length; i++) {
if (ispunct(str[i])) {
punct_count++;
}
}
int char_count = length - punct_count;
cout << "The length of string is : " << char_count << endl;
return 0;
}
上述代码中,我们使用了 string 类型的变量 str 以及 cctype 头文件中的 ispunct() 函数、计算字符串总长度以及字符数的方法。运行该程序,我们将得到以下输出:
The length of string is : 19
五、C函数…参数, LENGTH函数
在一些特殊情况下,我们可能需要使用变参函数来计算字符串长度。在 C++ 中,可以使用 … 参数以及 LENGTH 函数来实现这一目的。
#include
#include
using namespace std;
int len(const char* format, ...) {
va_list args;
va_start(args, format);
int count = vsnprintf(NULL, 0, format, args);
va_end(args);
return count;
}
int main()
{
cout << len("Hello %s", "World!") << endl;
return 0;
}
上述代码中,我们定义了 len() 函数,它包含了一个 … 参数。然后,我们使用 vsnprintf() 函数计算字符串长度。
vsnprintf() 函数是可变参数选择,具体说明请见函数文档,一般用于将格式化字符串写入字符数组。
运行上述程序,我们将获得以下输出:
Hello World!
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/195808.html
微信扫一扫
支付宝扫一扫