有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计算粘贴文本中的字符

我必须创建一个简单的程序,将计数文本中的字符,你将粘贴到cmd。问题是,我找不到让它正常工作的方法。 在我看来,它应该像

"please enter your text here" then you put the text there "the character count is: xyz"


共 (2) 个答案

  1. # 1 楼答案

    1. 想法很简单,使用控制台输入并计算其中的字符数

    2. 如果不需要文本之间的空格来计数,请使用.replaceprdefined string函数替换它,或者迭代字符串并相应地更新计数器变量。查看下面的代码以获取参考。
      {}

        public static int countCharacter(String s)
        {
          int l=s.length;
          for(int i=0;i<l;i++)
          {
            if(s.charAt(i)!=" ")
               {
                 counter++;
               }
           }
           return counter;  
         }
      
  2. # 2 楼答案

    给你一个想法,你可以尝试下面的代码

    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());
    

    使用条件获取多个用户输入

    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;
                   }
    
     }