简体   繁体   English

Java String + =需要简写说明

[英]Java String += Shorthand explanation needed

While I was creating a program to compress a string I ran into this strange problem, I will paste the code snippets with their outputs, I would like someone to clearly explain why this is happening. 当我创建一个压缩字符串的程序时遇到了这个奇怪的问题,我会将代码片段与它们的输出粘贴在一起,我希望有人能够清楚地解释为什么会发生这种情况。

The first code snippet: here if same letter appears consecutively, then the successive occurrences of the letter is replaced by the total count of same letters. 第一个代码片段:此处如果连续出现相同的字母,则字母的连续出现将被相同字母的总数替换。 Ex: aaabbb should be written as a3b3. 例如:aaabbb应写成a3b3。

public static String compress(String str){
    String compressed = "";
    char prev = str.charAt(0);
    int count = 1;
    for (int i = 1; i < str.length(); i++) {
        char curr = str.charAt(i);
        if (curr == prev) { // in case curr is equal to prev
            count++;
        } else { // in case curr is not equal to prev
            //compressed=compressed+prev+count;
            compressed+=prev+count;    // Shorthand used here
            count=1;
            prev=curr;
        }
    }
    compressed=compressed+prev+count; // Shorthand not used
    System.out.println(compressed);
    return compressed;
}

the output for this above code when inputted with aabbccaabbccaabbccaabb is 99100101991001019910010199b2, observe the last two elements of the output, this is because outside the loop, shorthand is not used. 当输入aabbccaabbccaabbccaabb时,上面这段代码的输出是99100101991001019910010199b2,观察输出的最后两个元素,这是因为在循环外,没有使用速记。 If I write the expression as compressed = compressed +prev+count inside the loop, I'll get the intended output. 如果我在循环中将表达式写为compressed = compressed + prev + count ,我将得到预期的输出。

I thought this output is because the operation is messing with the address of the String. 我认为这个输出是因为操作搞乱了String的地址。 But the next code confused me again. 但是下一个代码又让我感到困惑。

    String prev= "abc";
    String curr = "def";
    String result="";

    result+=prev+curr;
    System.out.println(result);

I think this is because the right hand operation is performing an ASCII addition, I cannot come to a conclusion, can anyone clarify. 我认为这是因为右手操作正在执行ASCII添加,我无法得出结论,任何人都可以澄清。

I am sleep deprived and hence I am not able to come to a conclusion, hence asking someone to clarify my trivial doubt. 我睡眠不足,因此我无法得出结论,因此要求某人澄清我的琐碎怀疑。

It has nothing to do with the reference. 它与参考无关。 When you did prev+count ascii value of the character in prev is added with the integer count. 当你做prev+count ascii时, prev中的字符值加上整数计数。 In this case : 在这种情况下 :

ascii of "a" is 97, and it occurred twice... so 97 +2 = 99 .. ascii的“a”是97,它发生了两次......所以97 +2 = 99 ..
ascii of "b" is 98, and it occurred twice... so 98 +2 = 100 .. “b”的ascii是98,它发生了两次......所以98 + 2 = 100 ..
ascii of "c" is 99, and it occurred twice... so 99 +2 = 101 .. ascii的“c”是99,它发生了两次......所以99 +2 = 101 ..
that's why the output is 99100101991001019910010199100 这就是输出为99100101991001019910010199100的原因

try this : compressed+=(""+prev)+count; // Shorthand used here 试试这个: compressed+=(""+prev)+count; // Shorthand used here compressed+=(""+prev)+count; // Shorthand used here

In this case, or in compressed+=""+prev+count case, since the operation happens from left to right, the + operator is applied on a string ( "" ) and char( prev ) and behaves like append and also returns a string. 在这种情况下,或者在compressed+=""+prev+count情况下,由于操作从左到右发生,+运算符应用于字符串( "" )和char( prev ),其行为类似于追加并且还返回串。 The resulting string is then appened with another int ( prev ) 然后用另一个int( prev )附加结果字符串

A better way is using a StringBuilder 更好的方法是使用StringBuilder

Take a look at this subject and at JLS 15.18.1 section : 看看这个主题JLS 15.18.1部分:

You see this behavior as a result of the combination of operator precedence and string conversion. 作为运算符优先级和字符串转换组合的结果,您会看到此行为。

JLS 15.18.1 states: JLS 15.18.1规定:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time. 如果只有一个操作数表达式是String类型,则对另一个操作数执行字符串转换(第5.1.11节)以在运行时生成字符串。

Therefore the right hand operands in your first expression are implicitly converted to string: string = string + ((char)65) + 5; 因此,第一个表达式中的右手操作数被隐式转换为字符串: string = string + ((char)65) + 5;

For the second expression however string += ((char)65) + 5; 但是对于第二个表达式, string += ((char)65) + 5; the += compound assignment operator has to be considered along with + . +=复合赋值运算符必须与+一起考虑。 Since += is weaker than + , the + operator is evaluated first. 由于+=弱于+ ,因此首先评估+运算符。 There we have a char and an int which results in a binary numeric promotion to int . 我们有一个char和一个int ,它导致对int二进制数字提升 Only then += is evaluated, but at this time the result of the expression involving the + operator has already been evaluated. 仅评估+= ,但此时已经评估了涉及+运算符的表达式的结果。

Whenever you add a char to an int in java first it converts the character into its equivalent ASCII value and then adds it to the integer 无论何时向java中的int添加char,它首先将该字符转换为其等效的ASCII值,然后将其添加到整数

eg suppose the following scenario , 例如,假设以下情况,

char c = 'a'; char c ='a'; // ASCII value of 'a' is 97 //'a'的ASCII值为97

int i = c + 5 ; int i = c + 5; // result will be 97 + 5 = 102 //结果将是97 + 5 = 102

I think this answers your first half question 我认为这回答了你的前半个问题

Now the Second part , 现在第二部分,

Whenever you use the shorthand operator in Java the expression at right hand side is evaluated first. 无论何时在Java中使用速记运算符,都会首先计算右侧的表达式。

Hence , for expresion 因此,表达

result += prev + curr it is evaluated as 结果+ = prev + curr它被评估为

result = result + (prev + curr); 结果=结果+(prev + curr);

Therefore , 因此,

result+=prev+curr; // Here first it appends "abc" with "def" and then the resultant "abcdef" is appended to as result .

you can convert your charater value "prev" to string and than append count to it. 你可以将你的charater值“prev”转换为字符串,然后将计数加到它上面。

compressed += Character.toString(prev) + count; compressed + = Character.toString(prev)+ count;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM