根据数组中各元素的大小,在终端中垂直打印与之匹配的*号

本文介绍了一个使用C语言编写的简单程序,该程序能够接收一个整数数组作为输入,并根据数组元素的值打印出相应的柱状图。通过定义两个辅助函数`max_elem`和`erect_pillar`来找出数组中的最大值并绘制柱状图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如:数组 int a[9] = {1,2,3,4,5,4,3,2,1}; 打印

*
***
*****
*******
*********




#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void erect_pillar(int a[], int size);
static int max_elem(int a[], int size);

int main(int argc, char **argv)
{
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
erect_pillar(a, 10);

exit(EXIT_SUCCESS);
}

static void erect_pillar(int a[], int size)
{
int high = max_elem(a, size);
int i, j;

for (i = 0; i < high; i++) {
for (j = 0; j < size; j++) {
if (a[j] >= high - i)
printf("* ");
else
printf(" ");
}
putchar('\n');
}
}

static int max_elem(int a[], int size)
{
int max;
int i;

for (max = 0, i = 0; i < size; i++)
if (max < a[i])
max = a[i];

return max;
}

{ "checkType": "FIELD", "fieldName": "SOLDTONAME", "expected": "深圳市终端有限公司", "actual": "Not Found", "valid": false }, { "checkType": "FIELD", "fieldName": "SOLDTOCOMPANY", "expected": "", "actual": "Not Found", "valid": false }, { "checkType": "FIELD", "fieldName": "SHIPTONAME", "expected": "深圳市终端有限公司上海库", "actual": "Not Found", "valid": false },还是 not foundpackage com.luxsan.llm.ai.service.impl; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.luxsan.llm.ai.domain.ValidationResult; import lombok.RequiredArgsConstructor; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; @RequiredArgsConstructor @Service public class PdfJsonCompareService { private final Map<String, Pattern> patternCache = new ConcurrentHashMap<>(); private final ObjectMapper objectMapper = new ObjectMapper(); /** * 读取pdf文件 * @param file * @return * @throws IOException */ public String readPdfText(MultipartFile file) throws IOException { try (PDDocument doc = PDDocument.load(file.getInputStream())) { PDFTextStripper stripper = new PDFTextStripper(); String rawText = stripper.getText(doc); return rawText.replaceAll("\\s+", " ").trim(); //统一空白符 } } public JsonNode parseJson(String jsonContent) throws Exception { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readTree(jsonContent); } public List<ValidationResult> compareContent(String pdfText, JsonNode jsonConfig) { List<ValidationResult> results = new ArrayList<>(); if (jsonConfig.isArray() && jsonConfig.size() > 0) { JsonNode dataNode = jsonConfig.get(0); // 1. 字段直接匹配 checkDirectFields(pdfText, dataNode, results); // 2. 连续字段匹配(城市+省份+邮编) checkConsecutiveFields(pdfText, dataNode, results); // 3. 正则检查 performRegexChecks(pdfText, results); } else { results.add(new ValidationResult("ERROR", "JSON格式错误", "期望一个包含对象的数组", "实际格式不匹配", false)); } return results; } /** * 检查 JSON 中所有键值是否直接存在于 PDF 文本中 */ private void checkDirectFields(String pdfText, JsonNode jsonConfig, List<ValidationResult> results) { Iterator<Map.Entry<String, JsonNode>> fields = jsonConfig.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); String fieldName = entry.getKey(); JsonNode valueNode = entry.getValue(); if (valueNode.isValueNode()) { String expectedValue = valueNode.asText().trim(); if (expectedValue.isEmpty()) { results.add(new ValidationResult("FIELD", fieldName, expectedValue, "Not Found", false)); continue; } // 支持通配符匹配* 表示任意字符) String pattern = expectedValue .replaceAll("\\*", ".*?") // 将 * 转为非贪婪匹配 .replaceAll("\\?", "."); // 将 ? 转为任意单个字符 boolean found = Pattern.compile(pattern).matcher(pdfText).find(); // 支持分词匹配(允许字段值跨行显示) if (!found) { found = keywordMatch(pdfText, expectedValue); } results.add(new ValidationResult( "FIELD", fieldName, expectedValue, found ? "Found" : "Not Found", found )); } } } /** * 分词关键词匹配:将字段值拆分为关键词列表,判断所有关键词是否存在于 PDF 文本中 */ private boolean keywordMatch(String pdfText, String expectedValue) { // 拆分字段值为关键词(按空格或标点分割) List<String> keywords = Arrays.asList(expectedValue.split("[\\s\\p{Punct}]+")); keywords.removeIf(String::isEmpty); // 判断所有关键词是否存在于 PDF 文本中 return keywords.stream() .allMatch(keyword -> { // 允许关键词跨行显示 return Pattern.compile(Pattern.quote(keyword)).matcher(pdfText).find(); }); } /** * 执行正则表达式检查 */ private void performRegexChecks(String pdfText, List<ValidationResult> results) { try (InputStream is = getClass().getClassLoader().getResourceAsStream("validation_rules.json")) { JsonNode config = objectMapper.readTree(is); JsonNode regexChecks = config.path("regexChecks"); // 从文件中读取 regexChecks 字段 if (regexChecks.isMissingNode()) return; Iterator<Map.Entry<String, JsonNode>> regexes = regexChecks.fields(); while (regexes.hasNext()) { Map.Entry<String, JsonNode> entry = regexes.next(); String checkName = entry.getKey(); String regexPattern = entry.getValue().asText(); Pattern pattern = getCachedPattern(regexPattern); Matcher matcher = pattern.matcher(pdfText); boolean found = matcher.find(); results.add(new ValidationResult( "REGEX", checkName, regexPattern, found ? "Matched" : "Not Matched", found )); } } catch (IOException e) { throw new RuntimeException(e); } } /** * 获取或创建缓存中的 Pattern 对象 */ private Pattern getCachedPattern(String regex) { return patternCache.computeIfAbsent(regex, Pattern::compile); } /** * 匹配连续字段(城市、省份、邮编) */ /** * 匹配连续字段(城市、省份、邮编),支持跨行显示 */ private void checkConsecutiveFields(String pdfText, JsonNode jsonConfig, List<ValidationResult> results) { // 预处理 PDF 文本:保留换行符,标准化空格 String processedText = pdfText .replaceAll("[\\t\\v]+", " ") // 替换制表符/垂直空格 .replaceAll(" +", " ") // 合并多余空格 .trim(); // 正则:匹配中文城市、省份 + 6位邮编,允许字段间夹杂任意内容(包括换行) Pattern pattern = Pattern.compile( "([\\u4e00-\\u9fa5]{2,4})[\\s\\S]*?([\\u4e00-\\u9fa5]{2,4})[\\s\\S]*?(\\d{6})", Pattern.DOTALL | Pattern.UNICODE_CASE ); Matcher matcher = pattern.matcher(processedText); if (matcher.find()) { String city = matcher.group(1).trim(); String state = matcher.group(2).trim(); String zip = matcher.group(3).trim(); // 更新 JSON 配置中的字段值 Iterator<Map.Entry<String, JsonNode>> fields = jsonConfig.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); String fieldName = entry.getKey(); JsonNode valueNode = entry.getValue(); if (valueNode.isValueNode()) { String expectedValue = valueNode.asText().trim(); String actualValue = "Not Found"; if (fieldName.equals("SHIPTOCITY")) { actualValue = city; } else if (fieldName.equals("SHIPTOSTATE")) { actualValue = state; } else if (fieldName.equals("SHIPTOZIP")) { actualValue = zip; } results.add(new ValidationResult( "FIELD", fieldName, expectedValue, actualValue, expectedValue.equals(actualValue) )); } } } else { // 记录详细错误信息 System.err.println("连续字段匹配失败,文本内容: " + processedText); System.err.println("正则表达式: " + pattern.pattern()); results.add(new ValidationResult( "ERROR", "连续字段匹配失败", "城市 省份 邮编", "Not Matched", false )); } } } 我已经优化了 为什么这个还是不行
最新发布
07-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值