代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>文字字符串轉(zhuǎn)矩陣</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<style>
body {
display: flex;
}
#inputCode {
width: 45%;
}
.runButton {
width: 8%;
padding: 10px;
}
#result {
width: 45%;
padding: 10px;
height: 500px;
overflow-y: auto;
}
</style>
</head>
<body>
<textarea id="inputCode"></textarea>
<button class="runButton" id="runButton">轉(zhuǎn)</button>
<pre id="result"></pre>
<script>
/**
* TextProcessor 類,用于處理文本相關(guān)操作
*/
class TextProcessor {
/**
* 從每一行中刪除尾隨空格
* @param {string} text - 要處理的文本
* @returns {string} - 處理后的文本
*/
static removeTrailingWhitespace(text) {
// 將文本按換行符分割為行數(shù)組
let lines = text.split('\n');
// 使用 map 方法對(duì)每行進(jìn)行處理迹炼,刪除尾隨空格
let processedLines = lines.map(line => line.replace(/\s+$/, ''));
// 將處理后的行數(shù)組重新組合為文本
return processedLines.join('\n');
}
/**
* 從文本中刪除空行
* @param {string} text - 要處理的文本
* @returns {string} - 處理后的文本
*/
static removeBlankLines(text) {
// 將文本按換行符分割為行數(shù)組
let lines = text.split('\n');
// 使用 filter 方法篩選出非空行
let nonBlankLines = lines.filter(line => line.trim().length > 0);
// 將非空行數(shù)組重新組合為文本
return nonBlankLines.join('\n');
}
/**
* 綜合處理文本砸彬,先刪除行尾空白符,再刪除空行
* @param {string} text - 要處理的文本
* @returns {string} - 最終處理后的文本
*/
static processText(text) {
// 先調(diào)用 removeTrailingWhitespace 方法刪除行尾空白符
let textWithoutTrailingWhitespace = this.removeTrailingWhitespace(text);
// 再調(diào)用 removeBlankLines 方法刪除空行
return this.removeBlankLines(textWithoutTrailingWhitespace);
}
}
/**
* StringMatrixCreator 類斯入,用于處理字符串相關(guān)操作
*/
class StringMatrixCreator {
/**
* 構(gòu)造函數(shù)砂碉,目前為空
*/
constructor() { }
/**
* 計(jì)算字符串中的行數(shù)
* @param {string} str - 輸入的字符串
* @returns {number} - 行數(shù)
* @throws {Error} - 如果輸入不是字符串,拋出錯(cuò)誤
*/
countLines(str) {
if (typeof str !== 'string') {
throw new Error('輸入必須是字符串');
}
return str.split('\n').length;
}
/**
* 找出字符串中最長(zhǎng)的行
* @param {string} str - 輸入的字符串
* @returns {string} - 最長(zhǎng)的行
* @throws {Error} - 如果輸入不是字符串刻两,拋出錯(cuò)誤
*/
findLongestLine(str) {
if (typeof str !== 'string') {
throw new Error('輸入必須是字符串');
}
const lines = str.split('\n');
let maxLength = 0;
let longestLine = '';
for (const line of lines) {
if (line.length > maxLength) {
maxLength = line.length;
longestLine = line;
}
}
return longestLine;
}
/**
* 根據(jù)輸入字符串創(chuàng)建矩陣
* @param {string} str - 輸入的字符串
* @returns {string[]} - 表示矩陣的字符串?dāng)?shù)組
* @throws {Error} - 如果輸入不是字符串增蹭,拋出錯(cuò)誤
*/
createMatrix(str) {
if (typeof str !== 'string') {
throw new Error('輸入必須是字符串');
}
const numLines = this.countLines(str);
console.log('確定行數(shù):', numLines);
const longestLine = this.findLongestLine(str);
const colCount = longestLine.length;
console.log('確定列數(shù):', colCount);
const matrix = [];
const lines = str.split('\n');
for (const line of lines) {
const paddingLength = colCount - line.length;
const paddedLine = line + '※'.repeat(paddingLength);
matrix.push(paddedLine);
}
return matrix;
}
}
document.getElementById('runButton').addEventListener('click', () => {
try {
const creator = new StringMatrixCreator();
const outputDiv = document.getElementById('result');
const inputString = document.getElementById('inputCode').value;
let processedMultiLineText = TextProcessor.processText(inputString);
console.log('處理后的文本:');
console.log(processedMultiLineText);
//console.log('轉(zhuǎn)為矩陣后:');
const mymatrix = creator.createMatrix(processedMultiLineText);
// 輸出矩陣的行數(shù)和列數(shù)
const rows = mymatrix.length;
const cols = mymatrix[0] ? mymatrix[0].length : 0;
console.log(`實(shí)際矩陣行數(shù)列數(shù): ${rows}, ${cols}`);
const validator = new MatrixValidator(mymatrix);
const isReal = validator.isRealMatrix();
console.log(`矩陣是否為實(shí)矩陣: ${isReal}`);
// 逆時(shí)針旋轉(zhuǎn)90°
const matrix2 = transposeAndReorderMatrix(mymatrix);
// 遍歷并打印轉(zhuǎn)置和重新排序后的矩陣的每一行
matrix2.forEach(row => {
console.log(`[${row.join(',')}]`)
});
// 將矩陣內(nèi)容輸出到 outputDiv
outputDiv.innerHTML = mymatrix.map(row => `${row}`).join('\n');
} catch (error) {
console.error(error.message);
}
});
class MatrixValidator {
constructor(mymatrix) {
this.mymatrix = mymatrix;
}
//定義:如果矩陣的每個(gè)元素都是非空字符串,也不是空白符磅摹,就稱這個(gè)矩陣為“實(shí)矩陣”滋迈。
isRealMatrix() {
for (let row of this.mymatrix) {
for (let element of row) {
if (typeof element !== 'string' || element.trim() === '') {
return false;
}
}
}
return true;
}
}
/**
* 函數(shù)用于對(duì)給定的矩陣進(jìn)行轉(zhuǎn)置和列的逆序排列∑浚看起來(lái)像是被逆時(shí)針90°了杀怠。
* @param matrix
* @returns 轉(zhuǎn)置后的矩陣
*/
function transposeAndReorderMatrix(matrix) {
// 獲取矩陣的行數(shù)
const rows = matrix.length;
// 獲取矩陣的列數(shù)
const cols = matrix[0].length;
const result = [];
// 從最后一列開始倒序遍歷列
for (let j = cols - 1; j >= 0; j--) {
const newRow = [];
// 遍歷每一行
for (let i = 0; i < rows; i++) {
// 將原矩陣中對(duì)應(yīng)位置的元素添加到新行中
newRow.push(matrix[i][j])
}
// 將新行添加到結(jié)果數(shù)組中
result.push(newRow)
}
// 返回結(jié)果矩陣
return result
}
</script>
</body>
</html>
運(yùn)行結(jié)果:
測(cè)試結(jié)果