编写c++程序,使用字符数组计算字符串的长度。不能使用strlen函数。
时间: 2024-10-27 20:09:52 浏览: 54
在C++中,计算字符串长度而不使用内置的strlen
函数,通常可以采用遍历字符数组的方式来实现。你可以创建一个变量记录遇到空字符('\0')的位置,这个位置就是字符串的结束。以下是示例代码:
#include <iostream>
// 定义一个名为findLength的函数,输入是一个字符数组(char*)
int findStringLength(char* str) {
int length = 0; // 初始化长度为0
while (str[length] != '\0') { // 遍历直到遇到空字符
length++; // 每次找到一个非空字符,长度加1
}
return length; // 返回字符串的实际长度
}
int main() {
char myString[] = "Hello, World!"; // 示例字符串
int stringLength = findStringLength(myString);
std::cout << "The length of the string is: " << stringLength << std::endl;
return 0;
}
在这个例子中,findStringLength
函数通过逐个检查字符数组中的元素,直到找到空字符为止,以此计算字符串的长度。
相关问题
C++怎么把字符数组转化为字符串
在C++中,将字符数组转换为字符串通常有两种方法:
使用
std::string
构造函数:charCharArray[5] = {'H', 'e', 'l', 'l', 'o'}; std::string strArrayAsString = std::string(charCharArray);
这里,
charCharArray
是一个字符数组,通过std::string
类型的构造函数将其转换为字符串。C-style字符串(
const char*
)转换:const char charArray[] = "Hello"; std::string strArrayAsString = std::string(charArray);
或者你可以手动复制字符串,并添加结束符
\0
:char charArray[] = "Hello"; size_t len = strlen(charArray) + 1; std::string strArrayAsString(len, '\0'); strcpy(strArrayAsString.c_str(), charArray);
分别用字符数组和字符指针作为函数参数,编写下列字符串处理函数,并给出测试结果: (1)求字符串长度的函数strLen(源字符串); (2)字符串复制函数strCpy(源字符串,目的字符串); (3)字符串连接函数strCat(字符串1,字符串2):字符串2连接到字符串1中; (4)字符串比较大小函数strCmp(字符串1,字符串2):若字符串1>字符串2,返回值大于0,比如1,若字符串1<字符串2,返回值小于0,如-1,若字符串1=字符串2,返回值等于0。
好的,我会根据您的要求回答您的问题。
(1)使用字符数组作为函数参数,求字符串长度的函数strLen:
int strLen(char s[]) {
int len = 0;
for (int i = 0; s[i] != '\0'; i++) {
len++;
}
return len;
}
测试代码:
char s[] = "hello world";
printf("字符串长度为:%d\n", strLen(s));
输出结果:字符串长度为:11
(2)使用字符指针作为函数参数,字符串复制函数strCpy:
void strCpy(char* dest, const char* src) {
while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
}
测试代码:
char s1[] = "hello";
char s2[10];
strCpy(s2, s1);
printf("复制后的字符串为:%s\n", s2);
输出结果:复制后的字符串为:hello
(3)使用字符数组作为函数参数,字符串连接函数strCat:
void strCat(char s1[], const char s2[]) {
int i, j;
i = j = 0;
while (s1[i] != '\0') {
i++;
}
while (s2[j] != '\0') {
s1[i] = s2[j];
i++;
j++;
}
s1[i] = '\0';
}
测试代码:
char s1[20] = "hello";
char s2[] = "world";
strCat(s1, s2);
printf("连接后的字符串为:%s\n", s1);
输出结果:连接后的字符串为:helloworld
(4)使用字符指针作为函数参数,字符串比较大小函数strCmp:
int strCmp(const char* s1, const char* s2) {
while (*s1 != '\0' && *s2 != '\0') {
if (*s1 > *s2) {
return 1;
} else if (*s1 < *s2) {
return -1;
}
s1++;
s2++;
}
if (*s1 == '\0' && *s2 == '\0') {
return 0;
} else if (*s1 == '\0') {
return -1;
} else {
return 1;
}
}
测试代码:
char s1[] = "hello";
char s2[] = "hello world";
printf("比较结果为:%d\n", strCmp(s1, s2));
输出结果:比较结果为:-1
相关推荐
















