0

Is there any function for printing a string up to space, e.g.

char* A = "This is a string."
print(A+5);
output: is

I don't want printing character by character.

4
  • Certainly not, you have to write your own function Commented Mar 9, 2012 at 9:33
  • Malloc a new string the same length as the passed one. Copy char-by-char into the new string until you find a space, then write a \0. printf the new string and then free it. Commented Mar 9, 2012 at 9:37
  • "I don't want printing character by character." Sorry, all C functions, be they library functions or made by you, print character by character. If you don't want this, you cannot print anything using the C language. Commented Mar 9, 2012 at 9:38
  • I thought printing a string can be faster than printing each character Commented Mar 9, 2012 at 9:41

2 Answers 2

4

printf("%s", buf) prints the characters from buf until a null terminator is encountered: there is no way to change that behaviour.

A possible solution that does not print character-by-character, does not modify the string to be printed and uses the format specifier %.*s which prints the first N characters from a string:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char* s = "this is a string";
    char* space_ptr = strchr(s, ' ');

    if (0 != space_ptr)
    {
        printf("%.*s\n", space_ptr - s, s);
    }
    else
    {
        /* No space - print all. */
        printf("%s\n", s);
    }

    return 0;
}

Output:

this

Sign up to request clarification or add additional context in comments.

Comments

1

An istream_iterator tokenizes on whitespace:

#include <sstream>
#include <iostream>
#include <iterator>

int main()
{
  const char* f = "this is a string";
  std::stringstream s(f);
  std::istream_iterator<std::string> beg(s);
  std::istream_iterator<std::string> end;
  std::advance(beg, 3);
  if(beg != end)
    std::cout << *beg << std::endl;
  else
    std::cerr << "too far" << std::endl;
  return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.