首页 > 解决方案 > 无法通过单词/或 12 个字符打印字符串

问题描述

首先,我们有一个字符串数组,我必须以这种方式打印这个数组,即空格前的一个单词或前 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));
    }
}

标签: c++c-strings

解决方案


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

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

推荐阅读