/
xlzpm
/
changeFile
Обзор
Документация
Войти
/
xlzpm
/
changeFile
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
Main.kt
78 строк
2 KB
Ilya Stone
add Main.kt
09 ноя 2024, 16:00
09 ноя 2024, 16:00
0cb850b
Код
Авторство
О чём код?
package org.example import java.io.File import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.regex.Pattern import kotlin.io.path.readText import kotlin.io.path.writeText fun main() { val scanner = Scanner(System.`in`) print("Введите путь к файлу: ") val path = scanner.nextLine() print("Введите новое имя для класса: ") val newClassName = scanner.nextLine() try { val filePath = Path.of(path) if (!Files.exists(filePath)) { println("Файл не найден по указанному пути.") return } var content = filePath.readText() val oldClassName = File(path).nameWithoutExtension content = content.replace(Regex("(?s)/\\*.*?\\*/|//.*"), "") content = content.replace(Regex("\\s+"), " ") content = content.replace(Regex("\\b$oldClassName\\b"), newClassName) val variablePattern = "\\b(?:int|double|String|boolean|float|char|long|byte|short|void|class)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\b" val matcher = Pattern.compile(variablePattern).matcher(content) val identifiers = mutableSetOf<String>() while (matcher.find()) { val identifier = matcher.group(1) if (identifier != newClassName && identifier != "main") identifiers.add(identifier) } val identifierMap = generateUniqueNames(identifiers) for ((original, newName) in identifierMap) { content = content.replace(Regex("\\b$original\\b"), newName) } val newFilePath = Path.of("${newClassName}.kt") newFilePath.writeText(content) println("File successfully created with the name: ${newClassName}.kt") } catch (e: Exception) { println("Error: ${e.message}") } } fun generateUniqueNames(identifiers: Set<String>): Map<String, String> { val map = mutableMapOf<String, String>() val usedNames = mutableSetOf<String>() val random = Random() for (identifier in identifiers) { var newName: String do { newName = if (identifiers.size <= 26) { ('a' + random.nextInt(26)).toString() } else { val letter1 = ('a' + random.nextInt(26)) val letter2 = ('a' + random.nextInt(26)) "$letter1$letter2" } } while (!usedNames.add(newName)) map[identifier] = newName } return map }