我这里有一个名为 message 的字符串。
Bruce Wayne,Batman,None,Gotham City,Robin,The Joker
Oliver Queen,Green Arrow,None,Star City,Speedy,Deathstroke
Clark Kent,Superman,Flight,Metropolis,None,Lex Luthor
Bart Allen,The Flash,Speed,Central City,Kid Flash,Professor Zoom
我需要计算每行中的字符数并以十六进制打印它们。
- 第一行应该是(从 Bruce 到 Joker)2b
- 第二行应该是(从奥利弗到丧钟)32
- 第三行应该是(从 Clark 到 Luthor)2e
- 第四行应该是(从 Bart 到 Zoom)36
package com.raghav.conversion;
import java.util.ArrayList;
public class StringToHex {
public static void Main(String[] args) {
String message = "Bruce Wayne,Batman,None,Gotham City,Robin,The Joker" +
"Oliver Queen,Green Arrow,None,Star City,Speedy,Deathstroke" +
"Clark Kent,Superman,Flight,Metropolis,None,Lex Luthor" +
"Bart Allen,The Flash,Speed,Central City,Kid Flash,Professor Zoom";
ArrayList<String> lines = new ArrayList<String>();
ArrayList<Integer> chars = new ArrayList<Integer>();
ArrayList<String> hex = new ArrayList<String>();
String line = "";
int c = 0;
for(int i = 0; i < message.length(); i++) {
lines.add(message.charAt(i), line);
line = line.replaceAll(",", "".replaceAll(" ", ""));
c = line.length();
chars.add(c);
hex.add(Integer.toHexString(c));
}
for (int i = 0; i < hex.size(); i++) {
String padded = "00000000".substring(hex.size()) + hex.get(i);
System.out.println(padded);
}
}
}
这是我到目前为止所得到的,但我在第 22 行得到一个 ArrayIndexOutOfBoundsException
lines.add(message.charAt(i), line);
有人可以帮我吗?谢谢。
最佳答案
String msg = "Bruce Wayne,Batman,None,Gotham City,Robin,The Joker\n" +
"Oliver Queen,Green Arrow,None,Star City,Speedy,Deathstroke\n" +
"Clark Kent,Superman,Flight,Metropolis,None,Lex Luthor\n" +
"Bart Allen,The Flash,Speed,Central City,Kid Flash,Professor Zoom";
String[] lines = msg.split("\n");
for(Integer i = 1; i <= lines.length; i++){
int numChars = 0;
String[] toks = lines[i - 1].split(",");
for(String tok : toks){
numChars += tok.replaceAll(" ", "").length();
}
System.out.println("Line " + i.toString() + " beginning with " +
toks[0] + " and ending with " + toks[toks.length - 1] +
" contains " + Integer.toHexString(numChars) +
" characters." );
}
这将满足您的要求。注意每行末尾的\n,这使得它们成为行。不确定你的第二个循环的用途。
关于java - 如何计算字符串中每一行的字符并将数字转换为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30809889/