这里有一个名为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
我需要计算每行中的字符数并以十六进制打印。
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);
有人可以帮帮我吗?感谢。
答案 0 :(得分:1)
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,它们就是行。不确定你的第二个循环是什么。
答案 1 :(得分:0)
打开
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";
到
List<String> message = new ArrayList<>();
message.add("Bruce Wayne,Batman,None,Gotham City,Robin,The Joker");
.....
和
for(int i = 0; i < message.length(); i++) {
到
for(String line : message){
然后使用line
进行计数......