I want to print to a word of length n in a string .Using by C ++ langues.I have not know funtions in string.h support that.
i'm happy when you help me!
thank you

Dani AI

Generated

asked how to print words of length n from a C++ string; suggested checking a word's length. A common, robust approach is: split the input into whitespace-delimited tokens, strip surrounding punctuation if needed, and test each token's size. The example below shows a simple, safe implementation using the C++ standard library (no C string.h).

#include <iostream>
#include <sstream>
#include <string>
#include <cctype>

int main() {
    std::string text = "This is an example, with punctuation.";
    std::istringstream iss(text);
    std::string token;
    std::size_t n = 2; // target word length

    while (iss >> token) {
        std::size_t start = 0;
        while (start < token.size() && std::ispunct(static_cast<unsigned char>(token[start]))) ++start;
        std::size_t end = token.size();
        while (end > start && std::ispunct(static_cast<unsigned char>(token[end - 1]))) --end;
        std::string word = token.substr(start, end - start);
        if (word.size() == n) std::cout << word << '\n';
    }
    return 0;
}

Notes: prefer <string> and std::string over old C headers; always cast to unsigned char when calling std::is* family to avoid undefined behavior; .size()/.length() reports bytes for UTF-8 (not Unicode code points) — use a UTF-8-aware library for multibyte text; to avoid copies, consider std::string_view (C++17) for large inputs. See std::basic_string::size for details.

Recommended Answers

All 2 Replies

Do you want to print the length of a string?

If you want to print the length of a string just use the "length()" function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.