如何将连续字母转换为Java中用短划线分隔的数字?

时间:2018-06-02 04:09:07

标签: java

我想将字母转换为数字,如果字母是连续的,我想用短划线( - )分隔。我将保留非字母字符不变,如下所示:

Input string: "20 pizzas an!d, 1 Apple a b c"

Output string: "20 16-9-26-26-1-19 1-14!4, 1 1-16-16-12-5 1 2 3"

注:a / A = 1,b / B = 2,... y / Y = 25,z / Z = 26

4 个答案:

答案 0 :(得分:1)

这非常简单容易。只需通过你的字符串并检查字母。如果找到,则将其替换为数字并添加-以防前一个字符也是一个字母:

public static String convert(String str) {
    StringBuilder buf = new StringBuilder();
    boolean alphabetic = false;

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);

        if (Character.isAlphabetic(ch)) {
            if (alphabetic)
                buf.append('-');
            buf.append(Character.toLowerCase(ch) - 'a' + 1);
            alphabetic = true;
        } else {
            buf.append(ch);
            alphabetic = false;
        }
    }

    return buf.toString();
}

答案 1 :(得分:0)

就像这样

 String alphabetic  = "abcdefghijklmnopqrstuvwxyz";
 char[] charArray = input.toCharArray();
 for (int i = 0, charArrayLength = charArray.length; i < charArrayLength; i++) {
        char ch = charArray[i];
        int index = alphabetic.indexOf(Character.toLowerCase(ch));
        if (alphabetic.indexOf(ch) >= 0 || index >= 0) {
            String replace = String.valueOf(index+ 1);
            if (i+1 != charArray.length && alphabetic.contains(String.valueOf(charArray[i+1])))
                replace =replace+"-";
            input = input.replace(ch + "", replace);
        }
    } 

答案 2 :(得分:0)

在注释中使用带有解释的java代码:

  1. 将输入字符串转换为大写
  2. 使用值
  3. 初始化hashmap
  4. 迭代字符串并在stringbuilder中追加char并附加- iff该字符不是最后一个字符,或者该字符是否由有效字符(AZ)继续,否则不要追加-

    public static void main(String[] args) {
        //Expected output = "20 16-9-26-26-1-19 1-14!4, 1 1-16-16-12-5 1 2 3"
        String inputString = "20 pizzas an!d, 1 Apple a b c";
        Map<Character, Integer> charValueMap = new HashMap<>();
        StringBuilder sb = new StringBuilder();
    
        //Converting all to upper-case for easy access of their value from map
        inputString = inputString.toUpperCase();
    
        //initialising map with values
        int value = 1;
        for (char ch = 'A'; ch <= 'Z'; ++ch) {
            charValueMap.put(ch, value++);
        }
    
        for (int i = 0; i < inputString.length(); i++) {
            char ch = inputString.charAt(i);
            if (charValueMap.containsKey(ch)) {
                sb.append(charValueMap.get(ch));
    
                /* condition checks to only append '-' if it is not the last character or
              there is some valid char[A-Z] after current char */
                if (!(i+1 == inputString.length() || !charValueMap.containsKey(inputString.charAt(i+1)))) {
                    sb.append("-");
                }
            } else {
                sb.append(ch);
            }
        }
    
        System.out.println(sb.toString());
    }
    

答案 3 :(得分:-1)

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

const string alphabetCapital="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string codedVersion1 = "#AKRTQIWEVHFYGDZXLPSOUBMNC";//J
string decode(string message);
string encode(string message);
bool welcome_(){//function to welcome the user 
string w_option = "";
bool w_dec_or_en = false;

cout<<"ENCODE/HIDE or DECODE a Message? "<<endl<<endl;

for(;;){
    cout<<"1 to ENCODE, 2 to DECODE: ";
    getline(cin, w_option);

    if (w_option == "1"){

            w_dec_or_en = true;
            break;

    }else if (w_option == "2"){
    w_dec_or_en = false;
    break;
        }else if (w_option.length() == 0){
        system("cls");
        }else system("cls");

}
return w_dec_or_en;
}

int main(){//main function
bool dec_or_en = false;
string message = "", option = "";
do{
dec_or_en = welcome_();
cout<<endl<<"Enter your Message: ";
getline(cin, message);

if (dec_or_en) {

        message = encode(message);//function to replace each character
        cout<<endl<<endl<<"The Encoded Message is: ";
            }
else if(!dec_or_en)
{
    message = decode(message);//function to decode the message
    cout<<endl<<endl<<"The Decoded Message is: ";
    }

cout<<message<<endl<<endl<<endl;

cout<<"Would You Like To Encode/Decode Another Message (y/n): ";
getline(cin,option);
cout<<endl<<endl;
}while((option != "n" || option != "N") && (option == "y" || option == "Y"));
return 0;
}


//functions
string encode(string message){//encoding message
int findCapital = 0;
for(int i = 0; i < message.size(); i++){// turn each character into capital letters.

message[i] = toupper(message[i]);

}

for(int i = 0; i < message.size(); i++){
findCapital = alphabetCapital.find(message.substr(i, 1));

    if(findCapital != string::npos){
       message.replace(i, 1, codedVersion1.substr(findCapital, 1));

    } else {
    //do nothing
    }
}
return message;
}


string decode(string message){// for decoding message
int findCoded = 0;
for(int i = 0; i < message.size(); i++){// turn each characters into capital letters.

message[i] = toupper(message[i]);

}

for(int i = 0; i < message.size(); i++){//decoding message
findCoded = codedVersion1.find(message.substr(i, 1));

    if(findCoded != string::npos){
       message.replace(i, 1, alphabetCapital.substr(findCoded, 1));

    } else {
    //do nothing
    }
}
return message;
}


P.S you can use the same logic i use here using C++ to encode and decode a message.. I don't know much about java.. So good Luck