【问题标题】:Java: is there an int method like charAt()? [duplicate]Java:有没有像 charAt() 这样的 int 方法? [复制]
【发布时间】:2015-03-01 06:48:33
【问题描述】:

我不想要“charAt(1);”返回字符串中位置 1 的字符...我希望它报告“matching = 1;”的所有实例

举个例子

int matching = 1;
int notMatching = 0;
int HI = matching;
int IH = notMatching; 
int searchString = theString.charAt(notMatching);

  int count = 0;
  int index = 0;

      while (0 < theString.length())
      {
      int  = theString.charAt(matching);
        if (theString.charAt(notMatching) == searchString)    
        {
        count = count + 1;
        }
        index = index + 1;
      }

不是一个很好的例子,但基本上是我想要的,或者这个程序应该做的是接受用户输入:

HIHIIH

并报告 HI 拼写为 IH 的实例......所以返回将是例如;

System.out.println("HI 拼写为 IH" + count + "times");

编辑:“重复”对我没有帮助

【问题讨论】:

  • 那么你想统计一个子串出现的次数?也就是你想知道字符串中出现“IH”的次数?
  • 有一个indexOf(String) 方法。这就是你想要使用的
  • 你认为你可以写一个例子吗?
  • @Donnie 看看我的回答。它解决了你的问题。顺便说一句,您编写的代码根本没有意义..
  • 我从您的 sn-p 的编译器中收到“找不到符号”错误。

标签: java string algorithm int charat


【解决方案1】:

你可以使用 StringBuffer 的 reverse 方法和 Pattern 和 Matcher 如下:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SearchReverseString {
    public static void main(String []args) {
        String str = "HIHIIH";
        String strToSearch = "HI";
        String strToSearchReversed = new StringBuffer(strToSearch).reverse().toString();
        Pattern strPattern = Pattern.compile(Pattern.quote(strToSearchReversed));
        Matcher matcher = strPattern.matcher(str);
        int counter = 0;
        while(matcher.find()) {
            ++counter;
        }
        System.out.println(strToSearch+" was spelt as "+strToSearchReversed+" "+counter+" times");
    }
}

输出是:

HI 被拼写为 IH 2 次​​p>

请注意,在我的程序中,str 表示输入字符串,strToSearch 表示要逆序搜索的字符串。 Pattern.quote 的使用确保所有元字符都被自动转义。

【讨论】:

  • 但是我得到了编译错误。
  • 嗯,你是在导入需要的类吗?
  • 我正在导入“java.util.*”,如果这是你要问的?模式和匹配器似乎不兼容
  • 我正在运行“java版本“1.7.0_60-ea””
  • 看来您不了解导入的工作原理。 '导入 java.util.*;'与'import java.util.regex.*;'不同使用我提供的导入或将导入语句更改为 import java.util.regex.*
猜你喜欢
  • 1970-01-01
  • 2021-06-09
  • 2017-02-27
  • 2013-07-07
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 2017-12-01
相关资源
最近更新 更多