Похожие чаты

This algorithm shows the position of the letter in the

alphabet. How to do the opposite when there is a number, and you need a letter?

public static void main(String args[]) {

String s = "HUYES";
String t = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (Character.isLetter(ch)) { // check if the character is a letter
if (!t.isEmpty()) {
t += " ";
}
int n = (int) ch - (int) 'A'; // if you want to check, then add 'A'+ 1. Where the beginning of the alphabet begins with 1
t += String.valueOf(n);
}
}
System.out.println(t);
}

6 ответов

12 просмотров

Get ascii code of 'A', add the number and then use the ascii code to convert to char char c = ((int)'A' + num)

Manav | avoid unnecessary messaging me
^ this can be a source of errors. So make sure you...

i just need to have a number from 0-25 and convert to alphabetical order and get the letter

holy moly, that's so ... cryptic. I would never understood what this code is doing without extra description. Why not just do it more straightforward? class EnglishAlphabet { static String alphabet = "abcdefghijklmnopqrstuvwxyz"; int positionInAlphabet(char letter) { return alphabet.indexOf(letter); } Character letterAtPosition(int pos) { if (0 <= pos && pos < alphabet.length()) { return alphabet.charAt(pos); } else { return null; // or throw if you want to be NPE-free } } } More readable. More maintainable - just imagine that some day comes PO and says "Ok, now we need to support Spanish and French".

Похожие вопросы

Обсуждают сегодня

Типа вызывать GetParent и проверять на соответствие GetModuleHandle?
The Bird of Hermes
67
Do any of you guys have interesting projects one could join? I'm a Middle Full-Stack developer (JS/TS, React & Node)
Lev Shapiro
40
I read yesterday that in the near future most cryptos will be gone. It's like there is a lot of bullshit within the crypto sphere and this corruption some way is going to be c...
Kanah The Great
48
Есть сайт. Там была древняя версия эво. Стоял плагин, который каждый коммент в Jot делал отдельной страницей. После обновления все слетело, теперь старница открывается отдельн...
Artem
1
Всем привет! Кто нибудь парсил в ручную JSON без библиотек и фреймворков? Есть может ссылки на оптимальный алгоритмы работы с текстом и примеры таких парсеров?
Lem
27
$res = json_decode($наша строка из респонса); $res1 = array_map(fn($o) => $o->name, $res->breadcrumbs[0]->entities); Как такое будет на Хаскеле?.. В начале весь джейсон, в ко...
Хаскель Моисеевич Гопник
27
Добрый день. А shovel'ы можно как-то сконфигурировать в definitions.json? Пробовал что-то вроде: { "users": [ { "name": "agent", "password_hash": "RBCbTzQd...
Aleksey
1
Hello, I have a question. Can anyone help me? I want to make my cryptocurrencies, like Tron, untraceable by anyone, even government organizations. I was told that to do this,...
 ➛ Eᒪᕼᗩᗰ
14
Вопрос по диагностике ошибок (я знаю в чем, в данном конкретном примере, я знаю, как исправить, пример модельный, понятно, что в реальности бывает намного запутаннее). module...
ⰄⰎⰋⰐⰐⰑⰛⰤⰧⰧⰩⰄ ⰊⰑⰁⰓⰡⰛⰦⰕⰫ
11
В чем сила брат, в NASM или FASM?
Isaac Kleiner
18
Карта сайта