【发布时间】:2011-01-15 10:05:55
【问题描述】:
有没有办法指定要打印出字符串的多少个字符(类似于ints 中的小数位)?
printf ("Here are the first 8 chars: %s\n", "A string that is more than 8 chars");
想要打印:Here are the first 8 chars: A string
【问题讨论】:
有没有办法指定要打印出字符串的多少个字符(类似于ints 中的小数位)?
printf ("Here are the first 8 chars: %s\n", "A string that is more than 8 chars");
想要打印:Here are the first 8 chars: A string
【问题讨论】:
printf(....."%.8s")
【讨论】:
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
%8s 将指定最小宽度为 8 个字符。你想在 8 处截断,所以使用 %.8s。
如果您想始终准确打印 8 个字符,您可以使用 %8.8s
【讨论】:
在 C++ 中,这很容易。
std::copy(someStr.c_str(), someStr.c_str()+n, std::ostream_iterator<char>(std::cout, ""));
编辑: 将它与字符串迭代器一起使用也更安全,因此您不会跑到最后。我不确定 printf 和 string 太短会发生什么,但我猜这可能更安全。
【讨论】:
std::cout << someStr.substr(0,8); 要明显得多。
基本方式是:
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
另一种通常更有用的方法是:
printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");
在这里,您将长度指定为 printf() 的 int 参数,它将格式中的“*”视为从参数中获取长度的请求。
你也可以使用符号:
printf ("Here are the first 8 chars: %*.*s\n",
8, 8, "A string that is more than 8 chars");
这也类似于“%8.8s”表示法,但再次允许您在运行时指定最小和最大长度 - 在以下场景中更现实:
printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);
printf() 的 POSIX 规范定义了这些机制。
【讨论】:
-)以使其达到指定的完整长度。
C 上下文中使用std::string_view 而不提升到std::string,这是一个很棒的技巧。
使用printf 你可以做到
printf("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
如果您使用的是 C++,则可以使用 STL 获得相同的结果:
using namespace std; // for clarity
string s("A string that is more than 8 chars");
cout << "Here are the first 8 chars: ";
copy(s.begin(), s.begin() + 8, ostream_iterator<char>(cout));
cout << endl;
或者,效率较低:
cout << "Here are the first 8 chars: " <<
string(s.begin(), s.begin() + 8) << endl;
【讨论】:
ostream_iterator<char>(cout)!相反,请使用ostreambuf_iterator<char>(cout)!性能上的差异应该比较大。
std::cout.write(s.data(), 8) 效率更高。或者在现代 C++ 中,std::cout << std::string_view{s.data(), 8}.
除了指定固定数量的字符外,还可以使用*,这意味着 printf 从参数中获取字符数:
#include <stdio.h>
int main(int argc, char *argv[])
{
const char hello[] = "Hello world";
printf("message: '%.3s'\n", hello);
printf("message: '%.*s'\n", 3, hello);
printf("message: '%.*s'\n", 5, hello);
return 0;
}
打印:
message: 'Hel'
message: 'Hel'
message: 'Hello'
【讨论】:
打印前四个字符:
printf("%.4s\n", "A string that is more than 8 chars");
请参阅this link 了解更多信息(检查 .precision -section)
【讨论】:
在 C++ 中,我是这样做的:
char *buffer = "My house is nice";
string showMsgStr(buffer, buffer + 5);
std::cout << showMsgStr << std::endl;
请注意这是不安全的,因为当传递第二个参数时,我可能会超出字符串的大小并产生内存访问冲突。您必须实施自己的检查以避免这种情况。
【讨论】: