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