递归方法countAlphabet [英] recursive method countAlphabet
本文介绍了递归方法countAlphabet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何接收字符串作为其参数并返回字符串中的字母数.
例如:
字符串:价格为$ 70."
字母数:10
这是我的代码,但是如何仅计算字母?
how to receive a String as its parameter and return the number of letters count in the String.
example:
String: "The price is $70."
Alphabets count: 10
this my code, but how to count only alphabets?
public class MyRecursion
{
//driver method
public static void main(String[] args)
{
//Example of a string to test with isPalindrome
String str1 = "Malam";
if( isPalindrome(str1))
System.out.println("Word: " + str1 + " is a Palindrome");
else
System.out.println("Word: " + str1 + " is NOT a Palindrome");
}//end main
//isPalindrome method
public static boolean isPalindrome(String str)
{
if (str.length() <= 1)
return true;
else
{
str = str.toLowerCase();
char first = str.charAt(0);
char last = str.charAt(str.length()-1);
if (first == last )
return isPalindrome(str.substring(1, str.length()-1));
else
return false;
}
}//end isPalindrome method
}//end class
推荐答案
70."
字母数:10
这是我的代码,但是如何仅计算字母?
70."
Alphabets count: 10
this my code, but how to count only alphabets?
public class MyRecursion
{
//driver method
public static void main(String[] args)
{
//Example of a string to test with isPalindrome
String str1 = "Malam";
if( isPalindrome(str1))
System.out.println("Word: " + str1 + " is a Palindrome");
else
System.out.println("Word: " + str1 + " is NOT a Palindrome");
}//end main
//isPalindrome method
public static boolean isPalindrome(String str)
{
if (str.length() <= 1)
return true;
else
{
str = str.toLowerCase();
char first = str.charAt(0);
char last = str.charAt(str.length()-1);
if (first == last )
return isPalindrome(str.substring(1, str.length()-1));
else
return false;
}
}//end isPalindrome method
}//end class
我'和CPallini在一起-这里有很强的作业感.所以,没有代码!
我不会进行递归-这里没有需要递归的内容.只需循环遍历字符串中的每个字符,并且-如果它是字母,则将其添加到计数中.
简单!
I''m with CPallini - there is a strong sense of homework here. So, no code!
I wouldn''t make this recursive - there is nothing here that requires recursion. Just loop through each of the characters in the string and - if it is alphabetic - add one to a count.
Simples!
示例递归 [ ANSI可打印字符 [ ^ ].选中"Dec"此表上的(十进制)列以供参考.
Recursion explained with examples[^]
The trick is to check the character if it is aint
orchar
or something else.
You can accomplish the given task by trying to convert the character into a int - a NumberFormatException will appear if it is not a int. I think this is what your teacher has in mind.
Other solution (more elegant): convert the character into a int and check if it is within the range (ANSI Printable Characters[^] of a letter. Check the "Dec" (decimal) column on this table for reference.
这篇关于递归方法countAlphabet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文