[英]how to count many times a character occurs in a string without using s loop
下面的代碼用於計算字符串中字符'x'的每次出現,但僅計數一次。
我不想使用循環。
public class recursionJava
{
public static void main(String args[])
{
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name)
{
int index = 0, result = 0;
if(name.charAt(index) == 'x')
{
result++;
}
else
{
result = result;
}
index++;
if (name.trim().length() != 0)
{
number(name);
}
return result;
}
}
您可以替換/刪除字符,然后比較結果字符串的長度:
String names = "xxhixx";
int numX = names.length() - names.replace("x", "").length(); // numX == 4
如果您不想使用循環,則可以使用遞歸:
public static int number (String name)
{
if (name.length () == 0)
return 0;
int count = name.charAt(0)=='x' ? 1 : 0;
return count + number(name.substring(1));
}
從Java 8開始,您可以使用流:
"xxhixx".chars().filter(c -> ((char)c)=='x').count()
先前的遞歸答案(來自Eran)是正確的,盡管它在新的Java版本中具有二次復雜性(子字符串在內部復制字符串)。 它可以是線性的:
public static int number(String names, int position) {
if (position >= names.length()) {
return 0;
}
int count = number(names, position + 1);
if ('x' == names.charAt(position)) {
count++;
}
return count;
}
您的代碼由於兩件事而無法工作:
number()
,都將變量index
設置為零並將result
返回零。 因此,該程序將始終停留在第一個字母上,並且還會重置到目前為止已找到的x數的記錄。 name.trim()
在這里幾乎沒有用,因為此方法僅刪除空格字符,例如空格,制表符等。 您可以通過以下方式解決這兩個問題
index
和result
全局變量,以及 index
來檢查您是否已到達String的末尾。 因此,最后,經過稍微修改(工作)的代碼版本將如下所示:
public class recursionJava {
private static int index = 0;
private static int result = 0;
public static void main(String[] args) {
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name){
if(name.charAt(index) == 'x')
result++;
index++;
if(name.length() - index > 0)
number(name);
return result;
}
}
您可以使用StringUtils.countMatches
StringUtils.countMatches(name,“ x”);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.