我有一个做成characterArray
的字符串
public static String Text = "hello hi bye";
我正在尝试查找hi
的字符位置,但是由于我现在比较的是每个索引错误,因此我目前正努力获取完整的单词。在不使用内置字符串函数的情况下如何比较字符数组中的完整单词?
这是我当前的代码;
public static HashMap<String, List<Integer>> SubtextResults = new HashMap<>();
public static String Text = "hello hi bye";
public static void addSubText(String text){
SubtextResults.put(text, new ArrayList<>());
char[] charArray = Text.toCharArray();
for(int i = 0; i < charArray.length; i++){
for(String key: SubtextResults.keySet()){
if(key.toLowerCase().contains(String.valueOf(charArray[i]).toLowerCase())){ // Wrong here, comparing letters instead of word/key
System.out.println(charArray[i] + " " + i);
SubtextResults.get(key).add(i);
}
}
}
}
任何帮助/建议将不胜感激。
答案 0 :(得分:0)
不使用任何String内置函数,仅用于CharArray进行转换
作为起点
public static void main(String[] args)
{
String mainText = "hello hi bye";
String searchText = "hi";
char[] mainTextArray = mainText.toCharArray();
char[] searchTextArray = searchText.toCharArray();
System.out.println(position(searchTextArray, mainTextArray));
}
public static int position(char[] searchTextArray, char[] mainTextArray) {
int foundposition =-1;
boolean foundFlag =false;
for (int i = 0; i < mainTextArray.length - searchTextArray.length+1; i++) {
for (int j = 0; j < searchTextArray.length; j++) {
if (mainTextArray[i + j] == searchTextArray[j]) {
if (j == searchTextArray.length - 1) {
foundposition = i;
foundFlag = true;
}
} else {
break;
}
}
}
if(foundFlag)
{ return foundposition; }
else
{ return -1;
}
}
更简单的方法,但使用库函数
尝试使用java提供的Matcher类,请遵循http://tutorials.jenkov.com/java-regex/matcher.html#find-start-end-methods
String text =
"This is the text which is to be searched " +
"for occurrences of the word 'is'.";
String patternString = "is";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
int count = 0;
while(matcher.find()) {
count++;
System.out.println("found: " + count + " : "
+ matcher.start() + " - " + matcher.end());
}
}
有关Matcher类的官方文档
答案 1 :(得分:0)
您可以使用Character ArrayList并使用subList方法,然后针对指定的索引将其转换回String,但是即使使用某种“ String”方法,我也看不到任何可以用来延长长度的角度一个以上的字符,不用某种方式使用String就可以逃脱。
df= np.load("D:\\Code\\data.npz")
print(df)
out:<numpy.lib.npyio.NpzFile object at 0x000000000EF0BFD0>
这里的replaceAll(startIndex,endIndex)是为了在我们toString()之后删除空格和制表符([,,])。但是,如果这样做,还可以使用在字符数组之前生成的原始String。
答案 2 :(得分:0)
如果您不想使用内置的字符串函数,则可能应该对循环和数组使用更多的内容。
您应该做的第一件事是将字符串拆分为字符数组,这基本上是由toCharArray()方法完成的,但是我猜您不能使用它,因为它是内置的。
您需要将字符串中的每个字符(刚创建的数组中的字符)与字符串中要定位的字符进行比较。这里的问题是您需要在新数组中保持正确的位置。如果您在字符串开头遇到“ h”,但在很晚之后遇到“ i”,则您遇到的单词可能不是“ hi”,因此,您应该比较每个字符并在必要时重置数组的位置,直到找到您要的字符为止寻找。
显然有更简单的方法来处理此问题(例如您显然无法使用的内置字符串方法),但我猜想这是一项作业,需要您了解字符串,字符,数组以及循环。一旦掌握了这些基础知识,这应该很容易。
我也不认为哈希表对于这样的问题不是必需的,除非出于某种原因当然是必需的。