Форум программистов, компьютерный форум, киберфорум
Java SE (J2SE)
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.80/25: Рейтинг темы: голосов - 25, средняя оценка - 4.80
0 / 0 / 0
Регистрация: 24.12.2018
Сообщений: 2

Проверка символов входящего сообщения на принадлежность алфавиту

27.12.2018, 22:03. Показов 4978. Ответов 13
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Нужен код проверки символов входящего сообщения на принадлежность алфавита. На Java
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
27.12.2018, 22:03
Ответы с готовыми решениями:

Проверка символов входящего сообщения на принадлежность алфавиту
Проверка символов входящего сообщения на принадлежность алфавиту. Есть вот такой код, но нужно его модернизировать, чтобы пользователь...

Проверка символов входящего сообщения на принадлежность алфавита
Проверка символов входящего сообщения на принадлежность алфавита.

Проверка входящего сообщения на приналежность алфавиту
Помогите, пожалуйста! Нужно написать программу, которая проверяет каждую букву слова, и если в слове есть элемент, не принадлежащий...

13
 Аватар для NiceJacket
109 / 89 / 25
Регистрация: 02.06.2018
Сообщений: 259
27.12.2018, 23:56
Не понял, что именно требуется, нет конкретики.
Если в строке хоть один не алфавитный символ, возвращает false:
Java
1
2
3
4
5
6
public static boolean isAlphabetic(String str) {
    for (Character character : str.toCharArray())
        if (!Character.isAlphabetic(character))
            return false;
    return true;
}
1
Автоматизируй это!
Эксперт Python
 Аватар для Welemir1
7391 / 4818 / 1246
Регистрация: 30.03.2015
Сообщений: 13,693
Записей в блоге: 29
28.12.2018, 06:42
полагаю имелся в виду конкретный алфавит. но какой вопрос-такой ответ
1
 Аватар для Aviz__
2749 / 2057 / 508
Регистрация: 17.02.2014
Сообщений: 9,478
28.12.2018, 10:00
Цитата Сообщение от NiceJacket Посмотреть сообщение
нет конкретики
вот, чтобы заработало, задают конкретику))
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.stream.IntStream;
 
public class Helper {
 
    private static boolean isBelongToAlfabet(String strCheck, char firstAlfabet, char lastAlfabet) {
        StringBuilder alfabet = new StringBuilder();
        alfabet.append(",.!?-:; ");
                IntStream.range(firstAlfabet, lastAlfabet).forEach(i -> alfabet.append((char) i));
        return strCheck.toLowerCase().chars()
                .filter(c -> alfabet.toString().indexOf(c) != -1).count() == strCheck.length();
    }
 
    public static void main(String[] args) {
        String txt = "Мама мыла раму!";
        System.out.println(isBelongToAlfabet(txt,'а','я'));
        txt = "Humpty Dumpty sat on a wall, Humpty Dumpty had a great fall;";
        System.out.println(isBelongToAlfabet(txt,'а','я'));
        System.out.println(isBelongToAlfabet(txt,'a','z'));
    }
}
0
1 / 1 / 0
Регистрация: 13.11.2018
Сообщений: 58
28.12.2018, 10:33
Aviz__,
Можете подправить код плиз
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.IntStream;
 
        public class Main {
        public static void main(String[] args) throws  IOException {
        final String DEFAULT_ENCODING = "utf-8";
        
        if(args.length < 2 || args.length > 3) {
            System.out.println("Неверное количество аргументов");
            System.exit(1);
        }
        
        String inputFilePath = args[0];
        String outputFilePath = args[1];    
        String fileEncoding = args.length == 2 ? DEFAULT_ENCODING : args[2];
        
        
        
 
        
        
 
        
        
        BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(inputFilePath), fileEncoding));
        File file = new File(outputFilePath);
        FileOutputStream fileOutputStream = new FileOutputStream(file, false);
        
        Writer writer = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
        
        String line;
        StringBuilder result = new StringBuilder();
        
        Map<String, String> dictionary = new Dictionary().getDictionary();
        
        while ((line = in.readLine()) != null) {
            String outLine = convertString(line, dictionary) + System.getProperty("line.separator");
            System.out.println(line);
            System.out.println(outLine);
            result.append(outLine) ;
        }
        
        writer.write(result.toString());
        
        in.close();
        writer.flush();
        writer.close();
                
        }
        
 
    public static String convertString(String str, Map<String, String> dictionary) {
        char[] chars = str.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (dictionary.containsKey(Character.toString(chars[i]))) {
                stringBuilder.append(dictionary.get(Character.toString(chars[i])));
                continue;
            }
            stringBuilder.append(chars[i]);
        }
        return stringBuilder.toString();
    }
}
 
class Dictionary {
    private Map<String, String> dictionary;
 
    public Dictionary() {
        dictionary = new HashMap<>();
        dictionary = new HashMap<>();
        dictionary.put("а", "a");
        dictionary.put("А", "A");
        dictionary.put("ә", "á");
        dictionary.put("Ә", "Á");
        dictionary.put("б", "b");
        dictionary.put("Б", "B");
        dictionary.put("д", "d");
        dictionary.put("Д", "D");
        dictionary.put("е", "e");
        dictionary.put("Е", "E");
        dictionary.put("ф", "f");
        dictionary.put("Ф", "F");
        dictionary.put("г", "g");
        dictionary.put("Г", "G");
        dictionary.put("ғ", "ǵ");
        dictionary.put("Ғ", "Ǵ");        
        dictionary.put("х", "h");
        dictionary.put("Х", "H");
        dictionary.put("һ", "һ");
        dictionary.put("Һ", "H");
        dictionary.put("і", "i");
        dictionary.put("І", "I");
        dictionary.put("и", "ı");
        dictionary.put("И", "I");
        dictionary.put("й", "ı");
        dictionary.put("Й", "I");
        dictionary.put("ж", "j");
        dictionary.put("Ж", "J");
        dictionary.put("к", "k");
        dictionary.put("К", "K");
        dictionary.put("л", "l");
        dictionary.put("Л", "L");
        dictionary.put("м", "m");
        dictionary.put("М", "M");
        dictionary.put("н", "n");
        dictionary.put("Н", "N");
        dictionary.put("ң", "ń");
        dictionary.put("Ң", "Ń");
        dictionary.put("о", "o");
        dictionary.put("О", "O");
        dictionary.put("ө", "ó");
        dictionary.put("Ө", "Ó");
        dictionary.put("п", "p");
        dictionary.put("П", "P");
        dictionary.put("қ", "q");
        dictionary.put("Қ", "Q");
        dictionary.put("р", "r");
        dictionary.put("Р", "R");
        dictionary.put("с", "s");
        dictionary.put("С", "S");
        dictionary.put("ш", "sh");
        dictionary.put("Ш", "Sh");
        dictionary.put("ч", "ch");
        dictionary.put("Ч", "Ch");
        dictionary.put("т", "t");
        dictionary.put("Т", "T");
        dictionary.put("ү", "ú");
        dictionary.put("Ү", "Ú");
        dictionary.put("ұ", "u");
        dictionary.put("Ұ", "U");
        dictionary.put("в", "v");
        dictionary.put("В", "V");
        dictionary.put("ы", "y");
        dictionary.put("Ы", "Y");
        dictionary.put("у", "ý");
        dictionary.put("У", "Ý");
        dictionary.put("з", "z");
        dictionary.put("З", "Z");
        dictionary.put("э", "e");
        dictionary.put("Э", "E");
        dictionary.put("ю", "ıý");
        dictionary.put("Ю", "Iý");
        dictionary.put("я", "ıa");
        dictionary.put("Я", "Ia");
        dictionary.put("ц", "ts");
        dictionary.put("Ц", "Ts");
        dictionary.put("ь", "");
        dictionary.put("Ь", "");
        dictionary.put("ъ", "");
        dictionary.put("Ъ", "");
        dictionary.put("ё", "ıo");
        dictionary.put("Ё", "Io");
        dictionary.put("щ", "sh");
        dictionary.put("Щ", "Sh");
    
        
        
    }
    
 
   public class hasCyrillic {
 
    private static boolean hasCyrillicSymbol (String strCheck, char Dictionary) {
        StringBuilder alfabet = new StringBuilder();
        alfabet.append(",.!?-:; ");
                IntStream.range(Dictionary).forEach(i -> alfabet.append((char) i));
        return strCheck.toLowerCase().chars()
                .filter(c -> alfabet.toString().indexOf(c) != -1).count() == strCheck.length();
    }
 
  
}
 
    public Map<String, String> getDictionary() {
        return dictionary;
        
    }
}
Добавлено через 6 минут
Aviz__,

Я в свой код добавил ваш код, там че то запутался((
0
 Аватар для Aviz__
2749 / 2057 / 508
Регистрация: 17.02.2014
Сообщений: 9,478
28.12.2018, 11:31
Цитата Сообщение от Gregorian12 Посмотреть сообщение
запутался(
https://www.cyberforum.ru/java/thread2250765.html - прекрасный распутыватель))
0
1 / 1 / 0
Регистрация: 13.11.2018
Сообщений: 58
28.12.2018, 11:33
Aviz__, Я проверил через отладку, там я не правильно написал вашу функцию. Можете помочь исправить пожалуйста умоляю)
0
28.12.2018, 11:37

Не по теме:

Цитата Сообщение от Gregorian12 Посмотреть сообщение
умоляю
не теряй достоинство, Бро! знать такой твой путь...

0
1 / 1 / 0
Регистрация: 13.11.2018
Сообщений: 58
28.12.2018, 11:38
Aviz__, Помоги изменить мне мой путь, стань супергероем спаси меня)
0
 Аватар для NiceJacket
109 / 89 / 25
Регистрация: 02.06.2018
Сообщений: 259
28.12.2018, 11:46
Цитата Сообщение от Gregorian12 Посмотреть сообщение
Aviz__, Помоги изменить мне мой путь, стань супергероем спаси меня)
Вы уже достали абсолютно всех и пишите не в той теме.
Итак, ваша задача, как вы её сформулировали:
Пройтись по значениям вашего hashmap и найти там кириллицу, вот функция:
(в вашем представленном коде конкретно буква К кириллическая)

Java
1
2
3
4
5
6
7
public static void findNotCyrillic(Map<String, String> dictionary) {
    Collection<String> values = dictionary.values();
    for (String str : values) {
        if (str.matches("[а-яА-Я]"))
            System.out.println("кириллица: " + str);
    }
}

Не по теме:


больше по этой теме не отвечаю

0
1 / 1 / 0
Регистрация: 13.11.2018
Сообщений: 58
28.12.2018, 11:51
NiceJacket,
Спасибо вам большое.
Но он у меня ничего не выводит, мне нужно найти кириллицу в латинице.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.IntStream;
 
        public class Main {
        public static void main(String[] args) throws  IOException {
        final String DEFAULT_ENCODING = "utf-8";
        
        if(args.length < 2 || args.length > 3) {
            System.out.println("Неверное количество аргументов");
            System.exit(1);
        }
        
        String inputFilePath = args[0];
        String outputFilePath = args[1];    
        String fileEncoding = args.length == 2 ? DEFAULT_ENCODING : args[2];
        
        
        
 
        
        
 
        
        
        BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(inputFilePath), fileEncoding));
        File file = new File(outputFilePath);
        FileOutputStream fileOutputStream = new FileOutputStream(file, false);
        
        Writer writer = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
        
        String line;
        StringBuilder result = new StringBuilder();
        
        Map<String, String> dictionary = new Dictionary().getDictionary();
        
        while ((line = in.readLine()) != null) {
            String outLine = convertString(line, dictionary) + System.getProperty("line.separator");
            System.out.println(line);
            System.out.println(outLine);
            result.append(outLine) ;
        }
        
        writer.write(result.toString());
        
        in.close();
        writer.flush();
        writer.close();
                
        }
        
    public static void findNotCyrillic(Map<String, String> dictionary) {
    Collection<String> values = dictionary.values();
    for (String str : values) {
        if (str.matches("[а-яА-Я]"))
            System.out.println("не кириллица: " + str);
    }
}
        
 
    public static String convertString(String str, Map<String, String> dictionary) {
        char[] chars = str.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (dictionary.containsKey(Character.toString(chars[i]))) {
                stringBuilder.append(dictionary.get(Character.toString(chars[i])));
                continue;
            }
            stringBuilder.append(chars[i]);
        }
        return stringBuilder.toString();
    }
}
 
class Dictionary {
    private Map<String, String> dictionary;
 
    public Dictionary() {
        dictionary = new HashMap<>();
        dictionary = new HashMap<>();
        dictionary.put("а", "a");
        dictionary.put("А", "A");
        dictionary.put("ә", "á");
        dictionary.put("Ә", "Á");
        dictionary.put("б", "b");
        dictionary.put("Б", "B");
        dictionary.put("д", "d");
        dictionary.put("Д", "D");
        dictionary.put("е", "e");
        dictionary.put("Е", "E");
        dictionary.put("ф", "f");
        dictionary.put("Ф", "F");
        dictionary.put("г", "g");
        dictionary.put("Г", "G");
        dictionary.put("ғ", "ǵ");
        dictionary.put("Ғ", "Ǵ");        
        dictionary.put("х", "h");
        dictionary.put("Х", "H");
        dictionary.put("һ", "һ");
        dictionary.put("Һ", "H");
        dictionary.put("і", "i");
        dictionary.put("І", "I");
        dictionary.put("и", "ı");
        dictionary.put("И", "I");
        dictionary.put("й", "ı");
        dictionary.put("Й", "I");
        dictionary.put("ж", "j");
        dictionary.put("Ж", "J");
        dictionary.put("к", "k");
        dictionary.put("К", "K");
        dictionary.put("л", "l");
        dictionary.put("Л", "L");
        dictionary.put("м", "m");
        dictionary.put("М", "M");
        dictionary.put("н", "n");
        dictionary.put("Н", "N");
        dictionary.put("ң", "ń");
        dictionary.put("Ң", "Ń");
        dictionary.put("о", "o");
        dictionary.put("О", "O");
        dictionary.put("ө", "ó");
        dictionary.put("Ө", "Ó");
        dictionary.put("п", "p");
        dictionary.put("П", "P");
        dictionary.put("қ", "q");
        dictionary.put("Қ", "Q");
        dictionary.put("р", "r");
        dictionary.put("Р", "R");
        dictionary.put("с", "s");
        dictionary.put("С", "S");
        dictionary.put("ш", "sh");
        dictionary.put("Ш", "Sh");
        dictionary.put("ч", "ch");
        dictionary.put("Ч", "Ch");
        dictionary.put("т", "t");
        dictionary.put("Т", "T");
        dictionary.put("ү", "ú");
        dictionary.put("Ү", "Ú");
        dictionary.put("ұ", "u");
        dictionary.put("Ұ", "U");
        dictionary.put("в", "v");
        dictionary.put("В", "V");
        dictionary.put("ы", "y");
        dictionary.put("Ы", "Y");
        dictionary.put("у", "ý");
        dictionary.put("У", "Ý");
        dictionary.put("з", "z");
        dictionary.put("З", "Z");
        dictionary.put("э", "e");
        dictionary.put("Э", "E");
        dictionary.put("ю", "ıý");
        dictionary.put("Ю", "Iý");
        dictionary.put("я", "ıa");
        dictionary.put("Я", "Ia");
        dictionary.put("ц", "ts");
        dictionary.put("Ц", "Ts");
        dictionary.put("ь", "");
        dictionary.put("Ь", "");
        dictionary.put("ъ", "");
        dictionary.put("Ъ", "");
        dictionary.put("ё", "ıo");
        dictionary.put("Ё", "Io");
        dictionary.put("щ", "sh");
        dictionary.put("Щ", "Sh");
    
        
        
    }
    
 
 
   
 
    public Map<String, String> getDictionary() {
        return dictionary;
        
    }
}
1
28.12.2018, 11:53

Не по теме:

Цитата Сообщение от NiceJacket Посмотреть сообщение
Вы уже достали абсолютно всех
Бро, скоро новый год, будем терпимие... Может ему армия карячиться, а он не хочет туда. Но, от судьбы уходить УЖЕ поздно.

0
28.12.2018, 12:19

Не по теме:

Aviz__, это ж наш старый друг, любитель матриц!

0
28.12.2018, 12:23

Не по теме:

Цитата Сообщение от Welemir1 Посмотреть сообщение
наш старый друг
он подрос, надо сказать))

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
28.12.2018, 12:23
Помогаю со студенческими работами здесь

Проверка на принадлежность к алфавиту
В общем увидел тему, решил помочь, не используя функции типа isalpha. В итоге получилась вот такая раскоряка, которая к тому же ещё и...

Проверка символов на принадлежность диапазону
Помогите пожалуйста с проеркой, делаю ее с помощью if else, а она почемуто не раотает. for ($i=0; $i&lt;count ($arr); $i++) { if (ord...

Создать множество М1 парных символов и множество М2 непарных символов входящего ряда
Реализирвоать задачу так : Множество использовать двумя способами, в виде процедуры и с помощью функции.В программе должно быть описание...

Определить принадлежность символа к тому или иному алфавиту
После ввода с клавиатуры произвольного строки определить его принадлежность к тому или иному алфавита. Символы, которые не входят в...

Проверка на принадлежность
Всем доброго времени суток! Помогите написать уловие принадлежности точки к графику! (лежит область в синей области или нет) Прикрепляю...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
14
Ответ Создать тему
Новые блоги и статьи
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка SDL3 из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru