1

我有两个字符串align_A并且align_B有一些字符,我如何打印第一行align_A然后在下面(下一行)打印第一行align_B然后在下面打印第二行,align_A在下一行打印第二行align_B等等。我使用这样的代码来插入可以位于行中的字符(80 个字符)。

int len=align_A.length()/80;
... 

我不写延续代码,因为我正在处理它并且还没有准备好。这很复杂,是否有另一种方法(此类功能)可以简单地执行此操作?
注意:字符串变量中没有行说明符,例如\0or \n

4

2 回答 2

1

我更喜欢char arraystdio

#include <cstdio>
// #include <cstdlib>
#define SCREEN_SIZE_STR "80"

int main(){
    const char s1[] =
        "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
        "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
        "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
        "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
        "12345678901234567890123456789012345678901234567890123456789012345678901234567890";
    const char s2[] = 
        "abcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmnop"
        "abcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmnop"
        "abcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmnop"
        "abcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmnop"
        "abcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmnop";

    int i1 = 0, i2 = 0;
    while(s1[i1] != '\0' && s2[i2] != '\0'){ // print both string
        i1 += printf("%."SCREEN_SIZE_STR"s", s1 + i1);
        i2 += printf("%."SCREEN_SIZE_STR"s", s2 + i2);
    }
    while(s1[i1] != '\0') // print the remaining of s1
        i1 += printf("%."SCREEN_SIZE_STR"s", s1 + i1);
    while(s2[i2] != '\0') // print the remaining of s2
        i2 += printf("%."SCREEN_SIZE_STR"s", s2 + i2);
    // system("pause");
    return 0;
}

如果您正在使用std::string

const char *s1 = string1.c_str();
const char *s2 = string2.c_str();
于 2013-05-06T14:21:25.967 回答
1

使用 std::string。有了它,您可以使用 find()查找下一个换行符。然后你可以使用substr()来分割字符串。

#include <iostream>
#include <string>

int main(){
    std::string str = "aasdasdasda\nasdasdasd\nasdasdasd";

    int index = str.find('\n'); // Find position of newline
    std::cout << str.substr(0, index) << std::endl; // Print string until newline
    std::cout << str.substr(0, 10 ) << std::endl; // Print the first 80 charcters
}
于 2013-05-06T13:57:22.867 回答