Java中如何在字符数组中查找指定字符?
字符数组查找实现方案
嘿,我来帮你把整数数组的查找逻辑改成字符数组版本!其实核心思路和你已经写的整数查找差不多,只是在输入处理和变量类型上需要做些调整,咱们一步步来:
关键调整点
- 整数输入用
Integer.parseInt(),字符输入需要读取输入字符串的第一个字符(要注意处理空输入的情况,避免抛出异常) - 查找时的比较逻辑不变(因为
char是基本类型,直接用==即可完成匹配) - 相关变量类型要从
int换成char,比如目标查找值searchKey的类型
完整实现代码
import java.io.BufferedReader; import java.io.InputStreamReader; public class CharArraySearch { public static void main(String[] args) { // 你给出的字符数组定义(假设A已填充随机字符,B已存入A的所有元素) char A[][] = new char[10][10]; char B[] = new char[55]; char C[] = new char[10]; char D[] = new char[10]; char searchKey = ' '; int foundCount = 0; int index; // 读取用户输入的目标字符 try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine(); // 处理空输入或无有效字符的情况 if (input == null || input.isEmpty()) { System.out.println("请输入一个有效的字符!"); return; } // 获取输入的第一个字符(默认用户输入单个字符) searchKey = input.charAt(0); } catch (Exception e) { System.out.println("input-output error"); return; } // 遍历B数组查找目标字符 for (index = 0; index < B.length; index++) { boolean isFound = false; if (B[index] == searchKey) { isFound = true; } if (isFound) { System.out.println(searchKey + " Value is found pozicija " + (index + 1)); foundCount++; } } // 遍历结束后统一判断是否找到目标 if (foundCount == 0) { System.out.println("Value " + searchKey + " not found...!"); } } }
代码细节说明
- 输入处理优化:增加了空输入的判断,避免
charAt(0)抛出StringIndexOutOfBoundsException - 变量类型适配:将
searchKey改为char类型,和字符数组的元素类型匹配 - 查找逻辑复用:保留了你熟悉的遍历+匹配逻辑,因为
char作为基本类型,直接用==就能完成值比较 - 结果输出优化:把“未找到”的判断移到循环结束后,避免原代码中循环内重复判断的冗余问题
内容的提问来源于stack exchange,提问作者Vlad Fedotov
相关产品推荐
相关产品推荐

