172

Is there a way to specify how many characters of a string to print out (similar to decimal places in ints)?

printf ("Here are the first 8 chars: %s\n", "A string that is more than 8 chars");

Would like it to print: Here are the first 8 chars: A string

Melebius
  • 6,183
  • 4
  • 39
  • 52
T.T.T.
  • 33,367
  • 47
  • 130
  • 168

8 Answers8

290

The basic way is:

printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");

The other, often more useful, way is:

printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");

Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument.

You can also use the notation:

printf ("Here are the first 8 chars: %*.*s\n",
        8, 8, "A string that is more than 8 chars");

This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like:

printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);

The POSIX specification for printf() defines these mechanisms.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 2
    To the last example: What if copied string is shorter than minlen? – truthseeker Oct 17 '13 at 12:12
  • 4
    The output will be blank padded (on the left unless you add a `-`) to make it up to the full specified length. – Jonathan Leffler Oct 17 '13 at 12:13
  • 2
    This is awesome trick if one wants to use `std::string_view` in `C` context without promotion to `std::string`. – Quarra Dec 01 '20 at 05:56
  • Unfortunately the printf() is unbalanced. It only fills up with spaces on the left side if string is right aligned, but if string is left aligned (by a '-') it doesn't fill up with spaces :-( – Jesko Feb 23 '23 at 08:51
  • @Jesko: Are you looking for `printf("[%-8.8s] [%8.8s]\n", "hello", "hello");`? The first blank-pads on the right; the second on the left. – Jonathan Leffler Feb 23 '23 at 16:44
31

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'
Neuron
  • 5,141
  • 5
  • 38
  • 59
hlovdal
  • 26,565
  • 10
  • 94
  • 165
17
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

developmentalinsanity
  • 6,109
  • 2
  • 22
  • 18
11

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;
Peter Alexander
  • 53,344
  • 14
  • 119
  • 168
  • 2
    Note: do **not** use `ostream_iterator(cout)`! Instead, use `ostreambuf_iterator(cout)`! The difference in performance should be rather large. – Dietmar Kühl Aug 11 '17 at 17:13
  • 1
    Way more efficient to instead use: [`std::cout.write(s.data(), 8)`](https://en.cppreference.com/w/cpp/io/basic_ostream/write). Or in modern C++, `std::cout << std::string_view{s.data(), 8}`. – Artyer Jul 20 '20 at 16:34
5

printf(....."%.8s")

pm100
  • 48,078
  • 23
  • 82
  • 145
5

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Chris H
  • 6,433
  • 5
  • 33
  • 51
4

Print first four characters:

printf("%.4s\n", "A string that is more than 8 chars");

See this link for more information (check .precision -section)

Anssi
  • 518
  • 4
  • 8
1

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.

rodolk
  • 5,606
  • 3
  • 28
  • 34