计算java中仅包含字母的字符串中的单词
我在课堂上遇到了一个需要解决的问题,我需要输入一个字符串,然后打印出字符串中有多少个数字。单词定义为仅包含字符A-z和A-z。我不能使用split()计算java中仅包含字母的字符串中的单词,java,Java,我在课堂上遇到了一个需要解决的问题,我需要输入一个字符串,然后打印出字符串中有多少个数字。单词定义为仅包含字符A-z和A-z。我不能使用split() 下面的逻辑应该适合你 public static void main(String[] args) { int wordCount=0; StringBuffer newDummy=new StringBuffer(); String dummy = "1223fgfdfsdfhi sdf
下面的逻辑应该适合你
public static void main(String[] args)
{
int wordCount=0;
StringBuffer newDummy=new StringBuffer();
String dummy = "1223fgfdfsdfhi sdfsdfh8678 df 435";
for(int i = 0; i < dummy.length(); i++)
{
if (Character.isDigit(dummy.charAt(i)))
{
wordCount++;
}else{
newDummy.append(dummy.charAt(i));
}
}
System.out.println("The number of words in this string is " + wordCount + "\n\n");
System.out.println("new String-->"+newDummy);
}
publicstaticvoidmain(字符串[]args)
{
int字数=0;
StringBuffer newDummy=新的StringBuffer();
字符串dummy=“1223fgfdfsdfhi sdfsdfh8678 df 435”;
对于(int i=0;i”+newDummy);
}
您调试过了吗?可能是重复的
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String currentWord;
String sentence;
int spacePos;
int wordCount;
int validChar;
System.out.print("Please enter a sentence: \n");
sentence = input.nextLine() + " ";
spacePos = sentence.indexOf(" ");
currentWord = sentence.substring(0, spacePos);
wordCount = 0;
validChar = 0;
if( spacePos == 0 )
{
spacePos = 1;
}//end of if
for( int i = 0; i < sentence.length(); i++ )
{
// VALIDATES IF A WORD IS A WORD
for(int j = 0; j < currentWord.length(); j++)
{
if( currentWord.charAt(j) > 'a' && currentWord.charAt(j) < 'z'
|| currentWord.charAt(j) > 'A' && currentWord.charAt(j) < 'Z')
{
validChar++;
}//end of if
if( validChar == currentWord.length() )
{
validChar = 0;
wordCount++;
}//end of if
}//end of for
// ROMOVES PREVIOUS WORD
sentence = sentence.replace(currentWord + " ", "");
currentWord = sentence.substring(0, spacePos);
spacePos = sentence.indexOf(" ") + 1;
} //end of for
System.out.println("\n\n FINAL WORD COUNT --->\t\t" + wordCount + "\n");
input.close();
}
public static void main(String[] args)
{
int wordCount=0;
StringBuffer newDummy=new StringBuffer();
String dummy = "1223fgfdfsdfhi sdfsdfh8678 df 435";
for(int i = 0; i < dummy.length(); i++)
{
if (Character.isDigit(dummy.charAt(i)))
{
wordCount++;
}else{
newDummy.append(dummy.charAt(i));
}
}
System.out.println("The number of words in this string is " + wordCount + "\n\n");
System.out.println("new String-->"+newDummy);
}