是否可以仅打印 C 字符串的特定部分,而不创建单独的子字符串?
假设我有以下内容:
char *string = "Hello, how are you?";
是否可以仅打印该字符串的最后 5 个字节?仅前 5 个字节怎么样?是否有某种 printf
的变体可以实现这一点?
Say I have the following:
char *string = "Hello, how are you?";
Is it possible to print out only the last 5 bytes of this string? What about the first 5 bytes only? Is there some variation of printf
that would allow for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,只需传递一个指向倒数第五个字符的指针即可。您可以通过
string + strlen(string) - 5
确定这一点。使用精度说明符:
%.5s
Yes, just pass a pointer to the fifth-to-the-last character. You can determine this by
string + strlen(string) - 5
.Use a precision specifier:
%.5s
是的,该字符串的最后五个字节可以通过以下方式完成:
前五个字节可以通过以下方式完成:
您也可以将两者结合起来以获取字符串中的子字符串。
how
一词可以打印为:You do必须小心字符串足够长才能正常工作。打印单字符字符串的最后五个字符将导致未定义的行为,因为索引以
-4
结束。换句话说,在尝试此操作之前请检查字符串长度。Yes, the last five bytes of that string can be done with:
The first five can be done with:
You can combine the two to get substrings within the string as well. The word
how
can be printed with:You do have to be careful that the string is long enough for this to work. Printing the last five characters of a one-character string will cause undefined behaviour since the index ends up at
-4
. In other words, check the string length before attempting this.正如 Rob 的最佳答案,但我会将其放入 foo()
as in Rob's top answer, but i would put it into a foo()
两种解决方案:
假设给定一个具有相同长度的可谓字符串 - 我将使用日期作为示例,并要求拆分为 HH:MM:SS.DDDDDDDD
[1] 可读实现:
[2] 简短实现:
要么:
要么:
应该有效。
您可以使用 sprintf 代替 printf 并复制到缓冲区。我还会检查正确的长度以避免不可预测的行为。
无论哪种情况 - 输出都将是:
Two solutions:
Say given a predicatable string with same length - I will use date as an example and asked to split into HH:MM:SS.DDDDDDD
[1] Readable Implementation:
[2] Short Implementation:
Either:
or:
Should work.
Instead of printf - you can use sprintf and copy to a buffer. I would also check for the correct length to avoid unpredictable behavior.
In either case - the output will be: