Using printf
you can do
printf("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
If you're using C++, you can achieve the same result using the 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;
Or, less efficiently:
cout << "Here are the first 8 chars: " <<
string(s.begin(), s.begin() + 8) << endl;
Print first four characters:
printf("%.4s\n", "A string that is more than 8 chars");
See this link for more information (check .precision -section)
In addition to specify a fixed amount of characters, you can also use *
which means that printf takes the number of characters from an argument:
#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;
}
Prints:
message: 'Hel'
message: 'Hel'
message: 'Hello'
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
%8s would specify a minimum width of 8 characters. You want to truncate at 8, so use %.8s.
If you want to always print exactly 8 characters you could use %8.8s
In C++, I do it in this way:
char *buffer = "My house is nice";
string showMsgStr(buffer, buffer + 5);
std::cout << showMsgStr << std::endl;
Please note this is not safe because when passing the second argument I can go beyond the size of the string and generate a memory access violation. You have to implement your own check for avoiding this.
In C++ it is easy.
std::copy(someStr.c_str(), someStr.c_str()+n, std::ostream_iterator<char>(std::cout, ""));
EDIT: It is also safer to use this with string iterators, so you don't run off the end. I'm not sure what happens with printf and string that are too short, but I'm guess this may be safer.
printf(....."%.8s")
Source: Stackoverflow.com