【发布时间】:2026-02-18 02:55:01
【问题描述】:
这是 strlen 的定义,我已经看过了。
strlen( ) 函数计算给定字符串中的字符数并返回整数值。找到空字符时停止计数。
现在根据我的说法,“kshitij”的 strlen 应该是 = 7,即不包括空字符,因为函数在遇到空字符时停止计数。 因此,如果我想打印单词“kshitij”及其反转的次数与单词中的字母一样多,那么正确的代码应该是。
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[1000];
gets(a);
int len=strlen(a);
for(int i=0; i<= len ; i++)
{
for(int j=len ; j>=0; j--)
{
cout<<a[j];
}
cout<<" ";
}
getch();
return 0;
}
因此它提供了相当正确的输出。(除了间距我不明白)
现在我很想知道如果我这样做会打印什么:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[1000];
gets(a);
int len=strlen(a);
for(int i=0; i<= len ; i++)
{
for(int j=len -1 ; j>=0; j--)
{
cout<<a[j];
}
cout<<" ";
}
getch();
return 0;
}
根据我的说法,它不应该产生最后一个字母“j”,但我看到的是它产生相同的输出,但间距比以前少 1。
我也试过了:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[1000];
gets(a);
int len=strlen(a);
for(int i=0; i<= len - 1 ; i++)
{
for(int j=len ; j>=0; j--)
{
cout<<a[j];
}
cout<<" ";
}
getch();
return 0;
}
在我看来,输出应该只包含“7 - 1 = 6”乘以反向字符串,但输出几乎相同。-1 对“len”的值没有影响。
有了这一切,我觉得strlen 函数也必须计算空字符,wiz strlen (a)= 8(包括‘\0’),但是我在输出窗口中只看到 7 个输出。
这让我想知道 strlen 函数是否也计算空字符,如果是,那么它必须在输出窗口中将其显示为空格。我无法理解完整的概念,感谢您的帮助吗?
我是编程新手,请放轻松。谢谢 :)。
【问题讨论】:
-
“这让我想知道 strlen 函数是否计算空字符” - 不,它没有。
-
停止使用
gets()。它已被弃用,并已从 C 语言的最新版本中删除。 -
This leaves me wondering if the strlen function counts the null character as well or not- 当你发现自己处于这个位置时,你应该查阅文档:en.cppreference.com/w/cpp/string/byte/strlen -
请停止发布程序输出的图像。只需将输出发布为 text.
-
由于您使用的是 C++,而不是 C,请使用标准字符串类型和相应的 iostream 方法,而不是 C 函数。
标签: c++ string-length