如何计算字符串中每行的字符并将数字转换为十六进制

时间:2015-06-12 18:27:04

标签: java arrays indexing hex

这里有一个名为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

我需要计算每行中的字符数并以十六进制打印。

  • 第一行应该是(从布鲁斯到小丑)2b
  • 第二行应该是(从Oliver到Deathstroke)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);

有人可以帮帮我吗?感谢。

2 个答案:

答案 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进行计数......