Home  >  Q&A  >  body text

java - c或c++里面字符数组,字符串之间的关系?

天梯赛的一道题,题目如下:

给定一个长度不超过10000的、仅由英文字母构成的字符串。请将字符重新调整顺序,按“GPLTGPLT....”这样的顺序输出,并忽略其它字符。当然,四种字符(不区分大小写)的个数不一定是一样多的,若某种字符已经输出完,则余下的字符仍按GPLT的顺序打印,直到所有字符都被输出。

输入格式:

输入在一行中给出一个长度不超过10000的、仅由英文字母构成的非空字符串。

输出格式:

在一行中按题目要求输出排序后的字符串。题目保证输出非空。

输入样例:
pcTclnGloRgLrtLhgljkLhGFauPewSKgt
输出样例:
GPLTGPLTGLTGLGLL

在csdn上面找到的别人用c++的做法,代码如下:

#include <iostream>  
#include <string>  
  
using namespace std;  
  
int main() {  
    string str;  
    int G, P, L, T;  
    G = P = L = T = 0;  
  
    cin >> str;  
    for( int i = 0; i < str.size(); i++ ) {  
        switch( str[i] ) {  
            case 'g':  
            case 'G': G++; break;  
            case 'p':  
            case 'P': P++; break;  
            case 'l':  
            case 'L': L++; break;  
            case 't':  
            case 'T': T++; break;  
        }  
    }  
  
    while( G || P || L || T ) {  
        if( G ) { cout << "G"; G--; }  
        if( P ) { cout << "P"; P--; }  
        if( L ) { cout << "L"; L--; }  
        if( T ) { cout << "T"; T--; }  
    }  
    return 0;  
}  

我发现好像大部分有关字符串的问题都可以用字符数组来接收,比如:

    char a[10005];
    char b[10005];
    gets(a);
    gets(b);
    

这小段代码里面,定义了字符数组,但是却用输入整个字符串的方式来读入的(这小段代码是别的程序里面的)
上面那个完整的代码,不明白的地方又两处:
1.定义的字符串str,却可以当做字符数组来用
2.while循环里里为什么可以直接判断?

请问这里面的实现是否和内存存储方式有关,java中会有类似的实现机制吗?

天蓬老师天蓬老师2763 days ago451

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:24:19

    The string实际上就是用char来存储数据的, 并重载了[] operator in C++, so data can be read like an array.

    typedef basic_string<char>    string;  
    
    class basic_string
    {
        operator[](size_type __pos)
        {
            ...
        }
    }

    In C or C++, non-zero values ​​are considered true, and ||是短路操作的,所以while(a || b || c)中, 如果a不为0或者为true,则直接进入循环体,不再判断bc,如果a为0或者为false,则继续判断b, and so on.

    Java中不允许重载操作符,并且用专门的boolean或Boolean来表示truefalse,所以没办法实现类似的机制。但是对于||This operator is also a short-circuit operation.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:24:19

    1. C++ supports operator overloading

    2. C++ can use int as a conditionIt is false only when the value is 0, and it is true if it is not 0

    Note: Java does not support operator overloading, so custom types cannot use []这种方式取值(只有数组可用[]),其次Java中条件判断必须是boolean类型是无法使用inttypes as judgment conditions.

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:24:19

    I agree with the point above. One of the goals of C++ is to maintain compatibility with C, not only in terms of syntax, but also in terms of usage habits.
    As a newly designed string type, its goal is to maintain high performance while maintaining compatibility with C usage habits. That's why there are so many operator overloadings [rare in other languages]. As for the second question, it's a C problem.

    reply
    0
  • Cancelreply