 | |  |  |
AIWROK软件字符串方法实用案例
- /**
- * 字符串方法实用案例 - 复杂版
- * 整合项目中所有字符串相关方法,实现一个完整的文本处理系统
- * 兼容ES5和Rhino引擎,适用于安卓AIWROK环境
- * //🍎交流QQ群711841924群一,苹果内测群,528816639
- * 运行说明:
- * 1. 在AIWROK环境中直接运行此文件
- * 2. 或在Rhino引擎中使用: rhino 字符串方法实用案例.js
- * 3. 或在支持ES5的JavaScript环境中运行
- */
- // 兼容Rhino引擎的printl函数
- if (typeof printl === 'undefined') {
- function printl(msg) {
- console.log(msg);
- }
- }
- // 兼容Rhino引擎的sleep函数
- if (typeof sleep === 'undefined') {
- var sleep = {
- millisecond: function(ms) {
- // 模拟sleep,在Rhino环境中会有真实实现
- }
- };
- }
- // 导入必要的工具函数
- function safeStringOperation(operation, fallbackValue) {
- try {
- return operation();
- } catch (e) {
- printl("字符串操作错误: " + (e.message || e));
- return fallbackValue !== undefined ? fallbackValue : "";
- }
- }
- // 字符串工具类
- function StringUtils() {}
- StringUtils.prototype.charAt = function(str, index) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof index !== 'number' || index % 1 !== 0) throw new Error('[错误] 参数index必须是整数');
- return str.charAt(index);
- };
- StringUtils.prototype.charCodeAt = function(str, index) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof index !== 'number' || index % 1 !== 0) throw new Error('[错误] 参数index必须是整数');
- return str.charCodeAt(index);
- };
- StringUtils.prototype.indexOf = function(str, searchValue, fromIndex) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof searchValue !== 'string') throw new Error('[错误] 参数searchValue必须是字符串');
- return str.indexOf(searchValue, fromIndex);
- };
- StringUtils.prototype.lastIndexOf = function(str, searchValue, fromIndex) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof searchValue !== 'string') throw new Error('[错误] 参数searchValue必须是字符串');
- return str.lastIndexOf(searchValue, fromIndex);
- };
- StringUtils.prototype.getLength = function(str) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.length;
- };
- StringUtils.prototype.match = function(str, regexp) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (!(regexp instanceof RegExp)) throw new Error('[错误] 参数regexp必须是正则表达式对象');
- return str.match(regexp);
- };
- StringUtils.prototype.replace = function(str, searchValue, replaceValue) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.replace(searchValue, replaceValue);
- };
- StringUtils.prototype.replaceAll = function(str, searchValue, replaceValue) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
-
- // 完全不依赖原生 replaceAll,确保所有环境兼容
- if (typeof searchValue === 'string') {
- var escaped = searchValue.replace(/[.*+?^${}()|[\]\\]/g, '\\[ DISCUZ_CODE_2 ]amp;');
- return str.replace(new RegExp(escaped, 'g'), replaceValue);
- } else if (searchValue instanceof RegExp) {
- var flags = '';
- if (searchValue.ignoreCase) flags += 'i';
- if (searchValue.multiline) flags += 'm';
- flags += 'g';
- return str.replace(new RegExp(searchValue.source, flags), replaceValue);
- }
- return str;
- };
- StringUtils.prototype.split = function(str, separator, limit) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.split(separator, limit);
- };
- StringUtils.prototype.startsWith = function(str, searchString, position) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- position = position || 0;
- return str.indexOf(searchString, position) === position;
- };
- StringUtils.prototype.endsWith = function(str, suffix) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- suffix = String(suffix);
- var length = str.length - suffix.length;
- return length >= 0 && str.indexOf(suffix, length) === length;
- };
- StringUtils.prototype.substr = function(str, start, length) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.substr(start, length);
- };
- StringUtils.prototype.substring = function(str, start, end) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.substring(start, end);
- };
- StringUtils.prototype.trim = function(str) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.trim();
- };
- StringUtils.prototype.capitalize = function(str) {
- str = String(str);
- if (str.length === 0) return str;
- return str.charAt(0).toUpperCase() + str.slice(1);
- };
- StringUtils.prototype.camelCase = function(str) {
- str = String(str);
- var words = str.split(/[\s_-]+/);
- var result = words[0].toLowerCase();
- for (var i = 1; i < words.length; i++) {
- result += this.capitalize(words[i].toLowerCase());
- }
- return result;
- };
- StringUtils.prototype.kebabCase = function(str) {
- str = String(str);
- return str.replace(/([a-z])([A-Z])/g, '$1-$2')
- .replace(/[\s_]+/g, '-')
- .toLowerCase();
- };
- StringUtils.prototype.snakeCase = function(str) {
- str = String(str);
- return str.replace(/([a-z])([A-Z])/g, '$1_$2')
- .replace(/[\s-]+/g, '_')
- .toLowerCase();
- };
- StringUtils.prototype.reverse = function(str) {
- str = String(str);
- var result = '';
- for (var i = str.length - 1; i >= 0; i--) {
- result += str.charAt(i);
- }
- return result;
- };
- StringUtils.prototype.contains = function(str, search) {
- str = String(str);
- search = String(search);
- return str.indexOf(search) !== -1;
- };
- // 文本处理系统
- function TextProcessor() {
- this.utils = new StringUtils();
- }
- /**
- * 处理用户输入的文本,执行多种字符串操作
- * @param {string} input - 用户输入的文本
- * @returns {Object} 处理结果
- */
- TextProcessor.prototype.processText = function(input) {
- var results = {};
-
- // 1. 基本信息
- results.original = input;
- results.length = this.utils.getLength(input);
- results.trimmed = this.utils.trim(input);
-
- // 2. 文本分析
- results.analysis = {
- hasNumbers: /\d/.test(input),
- hasLetters: /[a-zA-Z]/.test(input),
- hasChinese: /[\u4e00-\u9fff]/.test(input),
- hasPunctuation: /[.,!?;:'"()\[\]{}]/.test(input)
- };
-
- // 3. 格式转换
- results.transformations = {
- uppercase: input.toUpperCase(),
- lowercase: input.toLowerCase(),
- capitalize: this.utils.capitalize(input),
- camelCase: this.utils.camelCase(input),
- kebabCase: this.utils.kebabCase(input),
- snakeCase: this.utils.snakeCase(input),
- reversed: this.utils.reverse(input)
- };
-
- // 4. 文本提取
- results.extractions = {
- emails: this.utils.match(input, /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g) || [],
- phones: this.utils.match(input, /\d{3}-?\d{4}-?\d{4}/g) || [],
- urls: this.utils.match(input, /https?:\/\/[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?/g) || []
- };
-
- // 5. 文本统计
- results.stats = {
- wordCount: this.utils.split(input, /\s+/).length,
- sentenceCount: this.utils.split(input, /[.!?]+/).length,
- paragraphCount: this.utils.split(input, /\n\s*\n/).length
- };
-
- // 6. 敏感信息检测
- results.sensitive = {
- hasCreditCard: /\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}/.test(input),
- hasIdCard: /\d{17}[\dXx]/.test(input),
- hasPassword: /password|密码/i.test(input)
- };
-
- return results;
- };
- /**
- * 生成文本报告
- * @param {string} input - 输入文本
- * @returns {string} 格式化的报告
- */
- TextProcessor.prototype.generateReport = function(input) {
- var results = this.processText(input);
- var report = [];
-
- report.push("=== 文本处理报告 ===");
- report.push("原始文本: " + results.original);
- report.push("文本长度: " + results.length);
- report.push("去除空白: '" + results.trimmed + "'");
- report.push("");
-
- report.push("=== 文本分析 ===");
- report.push("包含数字: " + (results.analysis.hasNumbers ? "是" : "否"));
- report.push("包含字母: " + (results.analysis.hasLetters ? "是" : "否"));
- report.push("包含中文: " + (results.analysis.hasChinese ? "是" : "否"));
- report.push("包含标点: " + (results.analysis.hasPunctuation ? "是" : "否"));
- report.push("");
-
- report.push("=== 格式转换 ===");
- report.push("大写: " + results.transformations.uppercase);
- report.push("小写: " + results.transformations.lowercase);
- report.push("首字母大写: " + results.transformations.capitalize);
- report.push("驼峰命名: " + results.transformations.camelCase);
- report.push("短横线命名: " + results.transformations.kebabCase);
- report.push("下划线命名: " + results.transformations.snakeCase);
- report.push("反转: " + results.transformations.reversed);
- report.push("");
-
- report.push("=== 文本提取 ===");
- report.push("邮箱地址: " + (results.extractions.emails.length > 0 ? results.extractions.emails.join(", ") : "无"));
- report.push("电话号码: " + (results.extractions.phones.length > 0 ? results.extractions.phones.join(", ") : "无"));
- report.push("网址链接: " + (results.extractions.urls.length > 0 ? results.extractions.urls.join(", ") : "无"));
- report.push("");
-
- report.push("=== 文本统计 ===");
- report.push("单词数量: " + results.stats.wordCount);
- report.push("句子数量: " + results.stats.sentenceCount);
- report.push("段落数量: " + results.stats.paragraphCount);
- report.push("");
-
- report.push("=== 敏感信息检测 ===");
- report.push("包含信用卡号: " + (results.sensitive.hasCreditCard ? "是" : "否"));
- report.push("包含身份证号: " + (results.sensitive.hasIdCard ? "是" : "否"));
- report.push("包含密码信息: " + (results.sensitive.hasPassword ? "是" : "否"));
- report.push("==================");
-
- return report.join("\n");
- };
- /**
- * 文本清洗和规范化
- * @param {string} input - 输入文本
- * @returns {string} 清洗后的文本
- */
- TextProcessor.prototype.cleanText = function(input) {
- var result = input;
-
- // 1. 去除多余空白
- result = this.utils.replaceAll(result, /\s+/g, " ");
- result = this.utils.trim(result);
-
- // 2. 统一标点符号
- result = this.utils.replaceAll(result, /[。]/g, ".");
- result = this.utils.replaceAll(result, /[,]/g, ",");
- result = this.utils.replaceAll(result, /[!]/g, "!");
- result = this.utils.replaceAll(result, /[?]/g, "?");
-
- // 3. 移除敏感信息
- result = this.utils.replaceAll(result, /\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}/g, "[信用卡号]");
- result = this.utils.replaceAll(result, /\d{17}[\dXx]/g, "[身份证号]");
-
- // 4. 修复格式
- result = this.utils.replaceAll(result, /\.\s*/g, ". ");
- result = this.utils.replaceAll(result, /,\s*/g, ", ");
-
- return result;
- };
- /**
- * 文本相似度计算
- * @param {string} text1 - 第一个文本
- * @param {string} text2 - 第二个文本
- * @returns {number} 相似度 (0-1)
- */
- TextProcessor.prototype.calculateSimilarity = function(text1, text2) {
- // 简单的编辑距离算法实现
- function levenshteinDistance(a, b) {
- var matrix = [];
-
- for (var i = 0; i <= b.length; i++) {
- matrix[i] = [i];
- }
-
- for (var j = 0; j <= a.length; j++) {
- matrix[0][j] = j;
- }
-
- for (var i = 1; i <= b.length; i++) {
- for (var j = 1; j <= a.length; j++) {
- if (b.charAt(i - 1) === a.charAt(j - 1)) {
- matrix[i][j] = matrix[i - 1][j - 1];
- } else {
- matrix[i][j] = Math.min(
- matrix[i - 1][j - 1] + 1,
- matrix[i][j - 1] + 1,
- matrix[i - 1][j] + 1
- );
- }
- }
- }
-
- return matrix[b.length][a.length];
- }
-
- var distance = levenshteinDistance(text1, text2);
- var maxLength = Math.max(this.utils.getLength(text1), this.utils.getLength(text2));
- return maxLength === 0 ? 1 : 1 - (distance / maxLength);
- };
- // 测试示例
- function runTextProcessorDemo() {
- var processor = new TextProcessor();
-
- // 测试文本
- var testTexts = [
- "Hello World! This is a test.",
- "你好,世界!这是一个测试。",
- "Contact: john@example.com, Phone: 138-1234-5678",
- "Password: secret123, Credit Card: 1234-5678-9012-3456",
- "https://www.example.com is a website."
- ];
-
- printl("=== 🚀 字符串方法实用案例演示 ===");
- printl("整合项目中所有字符串相关方法");
- printl("==================================\n");
-
- for (var i = 0; i < testTexts.length; i++) {
- printl("\n=== 测试文本 " + (i + 1) + " ===");
- printl("原始文本: " + testTexts[i]);
- printl("");
-
- // 生成报告
- var report = processor.generateReport(testTexts[i]);
- printl(report);
-
- // 测试文本清洗
- var cleaned = processor.cleanText(testTexts[i]);
- printl("\n清洗后的文本: " + cleaned);
-
- // 测试相似度计算
- if (i > 0) {
- var similarity = processor.calculateSimilarity(testTexts[0], testTexts[i]);
- printl("与第一个文本的相似度: " + (similarity * 100).toFixed(2) + "%");
- }
-
- printl("\n" + "=".repeat(50));
- }
-
- printl("\n=== 演示完成 ===");
- }
- // 运行演示
- runTextProcessorDemo();
复制代码
| |  | |  |
|