Java プログラムを作成して、文字列 (距離) 内の 2 つの単語の間に含まれる単語数を判断したいと考えています。
たとえば、文字列で「このカメラの画質は素晴らしいです。」「品質」と「素晴らしい」の間の距離は 1 です。
Java プログラムを作成して、文字列 (距離) 内の 2 つの単語の間に含まれる単語数を判断したいと考えています。
たとえば、文字列で「このカメラの画質は素晴らしいです。」「品質」と「素晴らしい」の間の距離は 1 です。
ポインタだけで、コードを最適化できます。
public static void main(String[] args) {
String str = "The picture quality is great of this camera";
StringTokenizer st = new StringTokenizer(str);
int numberOfWords = 0;
boolean start = false;
while(st.hasMoreTokens()){
String token = st.nextToken();
if(token.equals("quality")){
start = true;
continue;
}
if(start) {
if(token.equals("great")){
start = false;
}
else {
numberOfWords++;
}
}
}
System.out.println(numberOfWords);
}
これが私の解決策です:
public static void main(String[] args) {
String input = "The picture quality is great of this camera";
// happy flows
System.out.println(findDistance(input, "quality", "great"));
System.out.println(findDistance(input, "picture", "of"));
// words in reversed order
System.out.println(findDistance(input, "camera", "great"));
// non occurring words
try {
System.out.println(findDistance(input, "picture", "camcorder"));
}
catch(IllegalArgumentException e) {
System.out.println("Expected exception caught, message was: " + e.getMessage());
}
}
private static int findDistance(String input, String word1, String word2) {
// check input
if (input == null) {
throw new IllegalArgumentException("Input cannot be null");
}
if (word1 == null || word2 == null) {
throw new IllegalArgumentException("Two words should be provided");
}
// determine boundaries
int pos1 = input.indexOf(word1);
int pos2 = input.indexOf(word2);
// check boundaries
if (pos1 < 0 || pos2 < 0) {
throw new IllegalArgumentException("Both words should occur in the input");
}
// swap boundaries if necessary to allow words in reversed order
if (pos1 > pos2) {
int tmp = pos1;
pos1 = pos2;
pos2 = tmp;
}
// obtain the range between the boundaries, including the first word
String range = input.substring(pos1, pos2);
// split the range on whitespace
// minus one to not count the first word
return range.split("\\s").length - 1;
}
良い一日を(素晴らしい画質です)!