有没有办法指定要打印的字符串的字符数(类似于int
s中的小数位)?
printf ("Here are the first 8 chars: %s\n", "A string that is more than 8 chars");
Run Code Online (Sandbox Code Playgroud)
想要打印: Here are the first 8 chars: A string
Jon*_*ler 206
基本方法是:
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
Run Code Online (Sandbox Code Playgroud)
另一种通常更有用的方法是:
printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");
Run Code Online (Sandbox Code Playgroud)
在这里,您将length指定为printf()的int参数,它将格式中的'*'视为从参数获取长度的请求.
您也可以使用表示法:
printf ("Here are the first 8 chars: %*.*s\n",
8, 8, "A string that is more than 8 chars");
Run Code Online (Sandbox Code Playgroud)
这也类似于"%8.8s"符号,但同样允许您在运行时指定最小和最大长度 - 在以下情况中更实际:
printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);
Run Code Online (Sandbox Code Playgroud)
POSIX规范printf()
定义了这些机制.
dev*_*ity 12
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
Run Code Online (Sandbox Code Playgroud)
%8s将指定最小宽度为8个字符.您希望截断为8,因此请使用%.8s.
如果您想要始终打印8个字符,则可以使用%8.8s
Pet*_*der 11
用printf
你可以做到
printf("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
Run Code Online (Sandbox Code Playgroud)
如果您使用的是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;
Run Code Online (Sandbox Code Playgroud)
或者,效率较低:
cout << "Here are the first 8 chars: " <<
string(s.begin(), s.begin() + 8) << endl;
Run Code Online (Sandbox Code Playgroud)
hlo*_*dal 10
除了指定固定数量的字符外,您还可以使用*
这意味着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;
}
Run Code Online (Sandbox Code Playgroud)
打印:
message: 'Hel'
message: 'Hel'
message: 'Hello'
Run Code Online (Sandbox Code Playgroud)