java 将字母转换为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10644420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:57:12  来源:igfitidea点击:

Converting Letters to Numbers

java

提问by Anonymous181

Let's say I have a program which converts letters to numbers such that:

假设我有一个将字母转换为数字的程序:

Input: abcd

输入: abcd

Output: 1234

输出:1234

  1. How can I convert abcd to 1234 efficiently
  2. and how can I extract every individual char from the token
  1. 如何有效地将 abcd 转换为 1234
  2. 以及如何从令牌中提取每个单独的字符

By the way, this is not homework. (this is for fun)

顺便说一下,这不是家庭作业。(这是为了好玩)

This is what I have so far:

这是我到目前为止:

public class Test {
public static void main(String[] args) throws IOException  {

    BufferedReader f = new BufferedReader(new FileReader("test.in"));

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out.txt")));

    StringTokenizer st = new StringTokenizer(f.readLine());

    int i1 = Integer.parseInt(st.nextToken());

            // How can I convert this into integers? (where a = 1, b = 2, and c = 3)

            out.println(????);

        out.close();
        System.exit(0);                              

    }

}

回答by Pablo Santa Cruz

Try this:

试试这个:

String s = "abcd";
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
    sb.append((char)(c - 'a' + 1));
}
// provided your string contains only lower case non-unicode (ASCII) characters.

回答by raddykrish

Have a map defined with keys as a,b,c etc with values 1,2,3 etc. Whenever you receive a token take that from the map and print.

有一个地图,键定义为 a、b、c 等,值为 1、2、3 等。每当您收到一个令牌时,从地图中取出并打印。

回答by Tony Ennis

Uppercase the letter, convert it to ASCII, subtract 'A', then add 1. If you're handling multi-character inputs, then iterate over the string. As you calculate as per the previous recommendation, multiply the previous sum by 10, then add the new value.

将字母大写,将其转换为 ASCII,减去“A”,然后加 1。如果您正在处理多字符输入,则遍历字符串。当您按照之前的建议进行计算时,将之前的总和乘以 10,然后添加新值。

回答by OmniOwl

Derp, I read the whole question wrong. My bad.

Derp,我读错了整个问题。我的错。

What you could do, is that you have a conversion algorithm I suppose. Each letter in the alphabet could have a value from the alphabet.

你可以做的是,我想你有一个转换算法。字母表中的每个字母都可以有一个来自字母表的值。

Then all you need to do, is match the letter you find, with a letter from you a string array, get it's index, and add 1 to it. Then you got the value. If that's how you wanna play.

然后您需要做的就是将您找到的字母与来自您的字符串数组的字母相匹配,获取它的索引,然后将其加 1。然后你得到了价值。如果这就是你想玩的方式。

回答by henryabra

I suppose this is the method you are looking for: String's charAt

我想这是您正在寻找的方法:String's charAt

A sample code that would do what you are after:

一个可以做你所追求的示例代码:

String a="abcd";
for (int i = 0; i < a.length(); ++i) {
   System.out.print(a.charAt(i)-'a'+1);
}

回答by porfiriopartida

You can try by convert the char to int and rest 96, you have to take care of out of range characters or use regex..

您可以尝试将 char 转换为 int 并保留 96,您必须处理超出范围的字符或使用正则表达式。

This sample converts abcd to 1234

此示例将 abcd 转换为 1234

a is the char with 97 (alt + 9 7) z is the char 122

a 是带有 97 (alt + 9 7) 的字符 z 是字符 122

A is the char 65, so you can handle by ranges or just turn the word to lowercase

A 是字符 65,因此您可以按范围处理或将单词转为小写

public static void main(String args[]){
        String abc = "abcd";
        String txt = "";

        for(int i=0; i<abc.length(); i++){
            txt+= ( (int)abc.charAt(i) - 96 );
        }

        System.out.println(txt);
    }

EDIT:

编辑:

public static void main(String args[]){
        String abc = "AbCd";
        String txt = "";
        abc = abc.toLowerCase();

        for(int i=0; i<abc.length(); i++){
            int letter = (int)abc.charAt(i);

            if(letter<97 || letter > 122)//in range
            {
                txt += ( (int)abc.charAt(i) - 96 );
            }

        }

        System.out.println(txt);
    }

回答by cristopher

import java.util.Scanner; import java.io.*;

导入 java.util.Scanner; 导入 java.io.*;

public class LetteredNumerationSystem{

公共类字母数字系统{

public static void main(String args[]){

File file = new File ("lettered.in");

    try{

    Scanner input = new Scanner(file);

    int dataCollect = input.nextInt();
    int sum=0;
    String lineInput ="";


      for(int i=0;i<=dataCollect;i++){
      while (input.hasNext()){
      lineInput=input.next();       
      char lineArray[] = lineInput.toCharArray();
         for(int j=0;j<lineArray.length;j++){
            if (lineArray[j] == 'A'){
              sum+=1;
            }
            else if (lineArray[j] == 'B'){
              sum+=10;
            }
            else if (lineArray[j] == 'C'){
               sum+=100;
            }
            else if (lineArray[j] == 'D'){
               sum+=1000;
            }
            else if (lineArray[j] == 'E'){
               sum+=10000;
            }
            else if (lineArray[j] == 'F'){
               sum+=100000;
            }
            else if (lineArray[j] == 'G'){
               sum+=1000000;
            }
            else if (lineArray[j] == 'X'){
               System.out.println(sum);
           sum=0;
            }
         }
        }
      }         
    }

    catch(FileNotFoundException e){
        System.out.println("ERROR");
        }   




}

}

}