2012-03-09 175 views
0

是否有任何功能可以將字符串打印到空間上,例如 打印一個字符串

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

我不想按字符打印字符。

+0

當然不是,你必須編寫自己的函數 – 2012-03-09 09:33:32

+0

Malloc一個新的字符串長度與傳入的字符串相同。將char-by-char複製到新字符串中,直到找到空格,然後寫入\ 0。 printf新的字符串,然後釋放它。 – 2012-03-09 09:37:34

+0

「我不想按字符打印字符。」對不起,所有的C函數,不管是它們的庫函數還是你自己製作的,都是逐字打印的。如果你不想要這個,你不能用C語言打印任何東西。 – Lundin 2012-03-09 09:38:55

回答

4

printf("%s", buf)打印buf中的字符,直到遇到空終止符:無法更改該行爲。

要打印不打印字符逐字符,不修改字符串的可能解決方案,並使用格式說明%.*s從一個字符串打印第一N字符:

#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; 
} 

輸出:

+0

這就是我想的,謝謝 – Deepak 2012-03-09 09:38:26

1

一個istream_iterator上標記化空格:

#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; 
}