英文:
Counting characters in pasted text
问题
我必须创建一个简单的程序,用于计算您将粘贴到命令提示符中的文本中的字符数。问题是,我找不到使其正常工作的方法。
在我的想法中,它应该以某种方式工作,类似于
>“请在此输入您的文本”
>然后您在那里输入文本
>“字符计数为:xyz”
英文:
I have to create a simple program that will count the characters in text that you will paste into the cmd. The problem is, that I can't find a way for it to work properly.
In my mind it should work somehow like
> "please enter your text here"
> then you put the text there
> "the character count is: xyz"
答案1
得分: 5
给您一个想法,您可以尝试下面的代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // 创建一个Scanner对象
System.out.println("请输入文本:");
String text = myObj.nextLine(); // 读取用户输入
System.out.println("字符总数为:" + text.length()); // 这将包括空格
// 如果您不想包括空格
String noSpaces = text.replace(" ", "");
System.out.println("字符总数为:" + noSpaces.length());
System.out.println("请输入文本:");
System.out.println("1=大写,2=计数,3=小写,4=移除空格!");
while (myObj.hasNextLine()) {
String text1 = myObj.nextLine(); // 读取用户输入
switch (text1) {
case "1":
// 在这里编写您的代码
break;
case "2":
// 在这里编写您的代码
break;
case "3":
// 在这里编写您的代码
break;
case "4":
// 在这里编写您的代码
break;
default:
break;
}
}
}
}
英文:
Giving you an idea you can try the code below
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Please enter your text!");
String text = myObj.nextLine(); // Read user input
System.out.println("the character count is: " + text.Length()); //This will also count spaces
//If you don't want to included white spaces
String noSpaces = text.replace(" ", "");
System.out.println("the character count is: " + noSpaces.Length());
Getting multiple userInput with conditions
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Please enter your text!");
System.out.println("1=UPPERCASE, 2-Count,3=lowercase,4=remove spaces!");
while(myObj.hasNextLine()){
String text = myObj.nextLine(); // Read user input
String text1 = myObj.nextLine();
switch (text1) {
case "1":
//your code here
break;
case "2":
//your code here
break;
case "3":
//your code here
break;
case "4":
//your code here
break;
default:
break;
}
}
答案2
得分: 1
- 这个想法很简单,获取控制台输入并计算其中的字符数。
- 如果你不希望计算文本之间的空格,请使用
.replace
预定义的字符串函数或迭代字符串并相应地更新计数变量。请参考下面的代码。
public static int counter=0;
public static int countCharacter(String s)
{
int l=s.length;
for(int i=0;i<l;i++)
{
if(s.charAt(i)!=" ")
{
counter++;
}
}
return counter;
}
英文:
-
The idea is simple, take console input and count the number of characters in it.<br>
-
If you not need the space between the text to get counted replace it with
.replace
prdefined string function or iterate over the string and update counter variable accordingly. Check the code below for refrence.
<br>public static int counter=0
public static int countCharacter(String s) { int l=s.length; for(int i=0;i<l;i++) { if(s.charAt(i)!=" ") { counter++; } } return counter; }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论