我是 Java 的新手,作为初学者,我被邀请在家尝试。
Write a program that will find out number of occurences of a smaller string in a bigger string as a part of it as well as an individual word. For example,
Bigger string = "I AM IN AMSTERDAM", smaller string = "AM".Output: As part of string: 3, as a part of word: 1.
虽然我确实搞定了第二部分(作为单词的一部分),甚至在第一个部分(作为字符串的一部分搜索单词)我也成功了,但我似乎不明白如何破解第一部分。它在示例输入中继续为我显示 1,而它应该是 3。
我确实犯了一个错误 - 如果您能指出错误并加以纠正,我将不胜感激。作为请求,我是一个很好奇的学习者 - 所以如果可能的话(按你的意愿) - 请解释为什么会这样。
import java.util.Scanner;
public class Program {
static Scanner sc = new Scanner(System.in);
static String search,searchstring;
static int n;
void input(){
System.out.println("What do you want to do?"); System.out.println("1.
Search as part of string?");
System.out.println("2. Search as part of word?");
int n = sc.nextInt();
System.out.println("Enter the main string"); searchstring =
sc.nextLine();
sc.nextLine(); //Clear buffer
System.out.println("Enter the search string"); search = sc.nextLine();
}
static int asPartOfWord(String main,String search){
int count = 0;
char c; String w = "";
for (int i = 0; i<main.length();i++){
c = main.charAt(i);
if (!(c==' ')){
w += c;
}
else {
if (w.equals(search)){
count++;
}
w = ""; // Flush old value of w
}
}
return count;
}
static int asPartOfString(String main,String search){
int count = 0;
char c; String w = ""; //Stores the word
for (int i = 0; i<main.length();i++){
c = main.charAt(i);
if (!(c==' ')){
w += c;
}
else {
if (w.length()==search.length()){
if (w.equals(search)){
count++;
}
}
w = ""; // Replace with new value, no string
}
}
return count;
}
public static void main(String[] args){
Program a = new Program();
a.input();
switch(n){
case 1: System.out.println("Total occurences: " +
asPartOfString(searchstring,search));
case 2: System.out.println("Total occurences: " +
asPartOfWord(searchstring,search));
default: System.out.println("ERROR: No valid number entered");
}
}
}
编辑:我将使用循环结构。
最佳答案
一个更简单的方法是使用正则表达式(这可能会打败自己编写它的想法,尽管学习正则表达式是一个好主意,因为它们非常强大:正如你所看到的,我的代码的核心是 4 行长countMatches
方法)。
public static void main(String... args) {
String bigger = "I AM IN AMSTERDAM";
String smaller = "AM";
System.out.println("Output: As part of string: " + countMatches(bigger, smaller) +
", as a part of word: " + countMatches(bigger, "\\b" + smaller + "\\b"));
}
private static int countMatches(String in, String regex) {
Matcher m = Pattern.compile(regex).matcher(in);
int count = 0;
while (m.find()) count++;
return count;
}
它是如何工作的?
- 我们创建一个
Matcher
,它将在您的字符串中找到一个特定的模式,然后迭代以找到下一个匹配项,直到没有剩余并增加一个计数器 - 模式本身:
"AM"
将在字符串中的任何位置找到任何出现的AM
。 "\\bAM\\b
"将只匹配整个单词(\\b
是单词分隔符)。
这可能不是您想要的,但我认为看到另一种方法会很有趣。从技术上讲,我正在使用循环 :-)
关于java - java字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30684490/