c++ - 无法通过单词/或 12 个字符打印字符串

标签 c++ c-strings

首先,我们有一个字符串数组,我必须以这种方式打印这个数组,空格前的一个单词或前 12 个字符 = 一个字符串。

例如,假设我们有字符串“hello world qwerty-----asd”,它必须打印为:

hello
world
qwerty------ (12 characters without space)
asd

因此,在任务中没有这 12 个字符条件(我猜只是 strtok 函数)会很容易做到,但在这种情况下,我不知道该怎么做,我有想法,但它只适用于 50%输入的,在这里,它很大而且很愚蠢,我知道它是关于字符串函数的,但是不能做算法,谢谢:

    int counter = 0;// words counter
int k1 = 0;// since I also need to print addresses of letters of third word, I have to know where 3rd word is
int jbegin=0,// beginning and end of 3rd word
    jend=0;
for (int k = 0; k < i; k++) {
    int lastspace = 0;//last index of new string( space or 12 characters)
    for (int j = 0; j < strlen(*(arr + k)); j++) {
        if (*(*(arr + k) + j) == ' ' ) {  //if space
            printf("\n");
            lastspace = j;
            counter++;
            if ( counter == 3 ) { // its only for addreses, doesnt change anything 
                k1 = k;
                jbegin = j + 1;
                jend = jbegin;
            }
        }
         if (j % 12 == 0  && (j-lastspace>11 || lastspace==0) ) { // if 12 characters without space - make  a new string
            printf(" \n");
            counter++;
            lastspace = j;
        }
        if (counter==3 ) { 
            jend++;
        }
        printf("%c", *(*(arr+k) + j)); // printing by char
    }
    printf("\n ");
}
if ( jend!=0 && jbegin!=0 ) {
    printf("\n Addreses of third word are :\n");
    for (int j = jbegin; j < jend; j++) {
        printf("%p \n", arr + k1 + j);
        printf("%c \n", *(*(arr + k1) + j));
    }
}

最佳答案

我试图理解你的代码,但老实说,我不知道你在那里做什么。如果逐个字符地打印,您只需要在遇到空格时添加一个换行符,并且您需要跟踪在同一行上已经打印了多少个字符。

#include <iostream>
int main() {
   char  x[] = "hello world qwerty------asd";
   int chars_on_same_line = 0;
   const int max_chars_on_same_line = 12;
   for (auto& c : x) {
       std::cout << c;
       ++chars_on_same_line;
       if (c == ' ' || chars_on_same_line == max_chars_on_same_line){
           std::cout << "\n";
           chars_on_same_line = 0;
       }
   }
}

如果由于某种原因你不能使用 auto 和基于 rage 的 for 循环,那么你需要获取字符串的长度并使用索引,如

size_t len = std::strlen(x);
for (size_t i = 0; i < len; ++i) {
    c = x[i];
    ...
}

关于c++ - 无法通过单词/或 12 个字符打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55639310/

相关文章:

c++ - 两个字符串的递归比较

C++ atof/_wtof,舍入误差

c - 为什么即使我没有尝试修改字符串,C 中的字符串也会被修改?

c++ - Template模板函数及参数推导

c++ - 编译器开关还是预处理器开关?

c++ - 默认情况下应调用 move 构造函数

c++ - 获取指向包含十六进制值的 C 字符串的指针

c - 使用 bsearch 和 cstring,没有结果

c++ - 从 Canny 检测和标记端点

c++ - 运算符()的含义?