如何在C中获得Char **的每一行的长度?
例如:
char* arr = "x xxxx\n"
"x xx\n"
"x xxx\n";
我尝试获取每一行的长度。我尝试了sizeof,strlen,它们都没有。 我只能得到总尺寸,例如:
int size = 0;
while(*arr) {
size++;
arr++;
}
现在,我只知道“ ARR”行的大小。我正在尝试找到每一行的长度。如果整行的整个长度相等,我可以找到它。 但是,如果它们与众不同怎么办?我应该如何处理这个?还是C允许这样做? 我试图想到Malloc,Realloc,但不确定这对此有用。请给我一些提示。 谢谢。
For instance:
char* arr = "x xxxx\n"
"x xx\n"
"x xxx\n";
I try to get the length of each row. I try sizeof, strlen, none of them works.
I only can get the total size, like:
int size = 0;
while(*arr) {
size++;
arr++;
}
Right now, I only know the size of row of "arr". I'm trying to find the length of each row. I can find it if the whole thing has equal length for each row.
But what if they are different? How should I approach this one? Or does C allow to do such things?
I was trying to think of malloc, realloc, but not sure that would work for this one. Please give me some hints.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试此(请记住
#include< string.h>
)Try this (remember to
#include <string.h>
)问题中定义的字符串不是
char **
,它是带有嵌入式新线的单个C字符串。您可以使用简单的迭代来计算其包含的行的长度:
您可以使用
strchr()
或strcspn()
来简化循环,该 strcspn()接受一个分隔器的字符串:使用
strcspn()
允许将特殊情况折叠到主循环中:The string defined in the question is not a
char **
, it is a single C string with embedded newlines.You can compute the lengths of the lines it contains with a simple iteration:
You can simplify the loop using
strchr()
orstrcspn()
, which accepts a string of separators:Using
strcspn()
allows for the special case to be folded into the main loop:您可以使用函数
strchr 在字符串中查找Newline字符,并使用该信息来计算单个行的长度:
此程序具有以下输出:
You can use the function
strchr
to find the newline characters in the string, and use that information for calculating the length of the individual lines:This program has the following output:
字符串的每个“行”以新的行字符
'\ n'
结束。因此,要确定一行的长度,您需要找到的是找到新行字符的位置。可以使用标准字符串函数
strchr
完成。这是一个演示程序。
程序输出是
行的长度的程序输出,未考虑新的行字符。如果您需要计算它,只需增加长度的值即可。
Each "row" of your string literal ends with the new line character
'\n'
.So to determine the length of a row what you need is to find the position of the new line character. That can be done using the standard string function
strchr
.Here is a demonstration program.
The program output is
The program output of the length of a row does not take into account the new line character. If you need to count it just increase the value of the length.