简体   繁体   English

访问在for循环内创建的字符串变量

[英]Access string variable created inside for-loop

I'm creating an android app that converts ascii to binary. 我正在创建一个将ascii转换为二进制的android应用。 But I can't figure out on how to access a string I made outside the for-loop. 但是我不知道如何访问在for循环之外创建的字符串。 if I type in binary(var name) android studio gives me an error. 如果我输入binary(var name)android studio给我一个错误。 Here's my code(it's only in the on-click listener) 这是我的代码(仅在单击式侦听器中)

String output = "";
String input = textEditText.getText().toString();
int length = input.length();

for (int i = 0;i < length;i++) {
    char c = input.charAt(i);
    int value = Integer.valueOf(c);
    String binaryOutpt2 = Integer.toBinaryString(value);
    String binary = output + binaryOutpt2;
}

Use StringBuilder instead of String for the variable output , like this: 使用StringBuilder而不是String作为变量output ,如下所示:

String input = textEditText.getText().toString();        
StringBuilder output = new StringBuilder();
int length = input.length();
for (int i = 0; i < length; i++) {
    char c = input.charAt(i);
    int value = (int) c;
    String s = Integer.toBinaryString(value);
    for (int j = 0; j < 8 - s.length(); j++) {
        output.append("0");
    }
    output.append(s);
}
String out = output.toString();

this way you append each binary value of each char at the initial output and finally you get the whole binary representation of the text. 这样,您可以在初始输出处附加每个char的每个二进制值,最后得到文本的整个二进制表示形式。
Also pad zeroes at the start of each binary value until you get 8 binary digits for each char. 还要在每个二进制值的开头填充零,直到为每个字符获得8个二进制数字。

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

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