我对计算C ++中字符总长度的函数有疑问。我发现了这个功能:
len = strlen(str1);
然而,当我在Xcode中尝试时,Xcode给了我一个黄色三角形,表示出现了错误或缺失。见下图
那么,有人可以帮我找到合适的函数来计算总长度吗?
答案 0 :(得分:1)
尝试像这样分配
size_t len;
而不是
int len;
答案 1 :(得分:0)
您尝试调用的函数在cstring
(和string.h
)中声明,因此您需要
#include <cstring>
但是如果使用ObjectiveC ++,请使用std::string
类而不是char
数组。
答案 2 :(得分:0)
当strlen返回unsigned long(size_t)时,将其放入int变量。第一个问题是unsigned long可能是一个非常大的数字。比int大得多。第二个问题是它的无符号,而int则不是。字符串的长度不能为负数,因此它也可以安全地无符号。无符号表示最后一位不会指定负值或非负值状态。
示例1:
#include <iostream> //for cout
#include <cstring> //for strlen()
using namespace std; //so we don't have to type std:: all the time
int main(){
char str1 = "Hello, World!";
unsigned long myLength = strlen(str1); // size_t myLength = strlen(str1) would work
cout << "String length: " << myLength << endl;
}
示例2 :(使用示例2,除非您执行的操作坚持使用char数组和strlen)
#include <iostream> //for cout
#include <string>
using namespace std; //so we don't have to type std:: all the time
int main(){
string myString("Hello, World!");
size_t myLength = myString.length(); // see length() in string, it also returns size_t
cout << "String length: " << myLength << endl;
}
如果可以,请阅读变量标牌和stl typedef(size_t是typedef)。字符串的doc页面是查看字符串可以为您提供的好地方。 string - C++ Reference