简体   繁体   中英

How can I assign numbers to characters in a string numerically without an array in Java?

So we haven't learned arrays yet in class, but we have an assignment that requires us to assign numerical values to letters. At least, we aren't told we need this, but that's the only way I can think of doing it. (Encrypting a string through shifting characters a specific way). I don't mean assign the same value for the same letter, I mean in like a "abba" string, it changes to "0123".

Thanks

Your best option then would be to use a loop. For example:

String str = "abba";
String numbers = "";


for (int i=0; i<str.length(); i++){
   numbers = numbers + Integer.toString(i);
}

This way you will go through each character in str and you will create a new string of numbers with the index of each character in str . The result for numbers will be "0123" just as you requested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM