在C ++中逐行打印两个字符串?

时间:2013-05-06 13:44:17

标签: c++

我有两个字符串align_Aalign_B有一些字符,如何打印align_A的第一行然后在下面(下一行)打印第一行{{1}然后在下面打印第二行align_B并在下一行打印第二行align_A,依此类推。我使用这样的代码插入可以在行中放置的字符(80个字符)。

align_B

我不写延续代码,因为我正在努力并没有准备好。 这是复杂性,还有另一种方式(这样的功能)可以简单地执行这个动作吗? 注意:字符串变量中没有行说明符,例如int len=align_A.length()/80; ... \0

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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();