java 查找字符串中的下一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13772593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:55:12  来源:igfitidea点击:

Find next character in a string?

javadatechar

提问by homersimpson

I have a java programming assignment where you have to input a date on a single line and it gives you a numerology (horoscope-like) report based on the date. It is assumed that the user will enter a formatted date, separated with spaces.

我有一个 java 编程作业,你必须在一行中输入一个日期,它会根据日期为你提供一个命理学(类似星座)的报告。假设用户将输入一个格式化的日期,用空格分隔。

I can retrieve the month, day, and year of the input by using in.nextInt(). However, I also have to check that the user used a correct separating character for each part of the date, which means I just have to check whether the user used forward slashes.

我可以使用 in.nextInt() 检索输入的月、日和年。但是,我还必须检查用户是否对日期的每个部分使用了正确的分隔符,这意味着我只需要检查用户是否使用了正斜杠。

When looking at my code below, I currently use charAt() to find the separating characters. The problem is that the date won't always be 14 characters long. So a date in the form of 10 / 17 / 2004 is 14 characters long, but a date of 4 / 7 / 1992 is only 12 characters long, meaning that "slash1" won't always be in.charAt(3), in the latter situation it would be in.charAt(2).

在查看下面的代码时,我目前使用 charAt() 来查找分隔字符。问题是日期并不总是 14 个字符长。所以 10 / 17 / 2004 形式的日期有 14 个字符长,但 4 / 7 / 1992 的日期只有 12 个字符长,这意味着“slash1”不会总是在.charAt(3) 中,在后一种情况将是 in.charAt(2)。

Does java have a method that allows something like in.nextChar()? I know that it doesn't, but how could I just find a next character in the date?

java 是否有允许类似 in.nextChar() 的方法?我知道它没有,但是我怎么能在日期中找到下一个字符呢?

EDIT: I forgot to reflect this originally, but my professor said that we are NOT allowed to use the String.split() method, for some reason. The thing is, I get the month, day, and year perfectly fine. I just need to check that the person used a forward slash to separate the date. If a dash is entered, the date is invalid.

编辑:我最初忘记反映这一点,但我的教授说由于某种原因我们不允许使用 String.split() 方法。问题是,我得到的月、日和年完全没问题。我只需要检查此人是否使用正斜杠分隔日期。如果输入破折号,则日期无效。

public void getDate()
{
    char slash1, slash2;

    do
    {
        System.out.print("Please enter your birth date (mm / dd / yyyy): ");
        Scanner in = new Scanner(System.in);
        String date = in.nextLine();

        month = in.nextInt();
        day = in.nextInt();
        year = in.nextInt();

        slash1 = date.charAt(3);
        slash2 = date.charAt(8);
    } while (validDate(slash1, slash2) == false);

    calcNum();
}

采纳答案by Scooter

I would use Scanner just to get a line. Then split() the line on whitespace and check the fields:

我会使用扫描仪只是为了得到一条线。然后 split() 空格上的行并检查字段:

import java.util.Scanner;
import java.util.regex.Pattern;

public class GetDate {

   int month, day, year;

   public static void main(String[] args)
   {
      GetDate theApp = new GetDate();
      theApp.getDate();

   }

   public void getDate()
   {
      String date;
      do
      {
         System.out.print("Please enter your birth date (mm / dd / yyyy): ");
         Scanner in = new Scanner(System.in);
         date = in.nextLine();
      } while (validDate(date) == false);


      calcNum();
   }

   boolean validDate(String date)
   {
      // split the string based on white space
      String [] fields = date.split("\s");

      // must have five fields
      if ( fields.length != 5 )
      {
         return false;
      }

      // must have '/' separators
      if ( ! ( fields[1].equals("/") && fields[3].equals("/") ) )
         return false;

      // must have integer strings
      if ( ! ( Pattern.matches("^\d*$", fields[0]) && 
               Pattern.matches("^\d*$", fields[2]) &&
               Pattern.matches("^\d*$", fields[4]) ) )
         return false;

      // data was good, convert strings to integer 
      // should also check for integer within range at this point
      month = Integer.parseInt(fields[0]);
      day = Integer.parseInt(fields[2]);
      year = Integer.parseInt(fields[4]);

      return true;
   }

   void calcNum() {}
}

回答by Kent

you could consider to split the input date string with " / ", then you get a String array. the next step is converting each string in that array to int.

你可以考虑用 分割输入日期字符串" / ",然后你得到一个字符串数组。下一步是将该数组中的每个字符串转换为 int。

回答by Bohemian

Rather than thinking about what characters are used as separators, focus on the content you want, which is digits.

与其考虑使用哪些字符作为分隔符,不如关注您想要的内容,即数字。

This code splits on nondigits, do it doesn't matter how many digits are in each group or what characters are used as separators:

此代码在数字上拆分,每个组中有多少个数字或使用哪些字符作为分隔符都无关紧要:

String[] parts = input.split("\D+");

It's also hardly any code, so there's much less chance for a bug.

它也几乎没有任何代码,因此出现错误的可能性要小得多。

Now that you have the numerical parts in the String[], you can get on with your calculations.

现在您在 String[] 中有数字部分,您可以继续进行计算。

Here's some code you could use following the above split:

以下是您可以按照上述拆分使用的一些代码:

if (parts.length != 3) {
    // bad input
}

// assuming date entered in standard format of dd/mm/yyyy
// and not in retarded American format, but it's up to you
int day = Integer.parseInt(parts[0];
int month = Integer.parseInt(parts[1];
int year = Integer.parseInt(parts[2];

回答by erickson

Look ahead in the stream to make sure it contains what you expect.

在流中向前看以确保它包含您期望的内容。

private static final Pattern SLASH = Pattern.compile("\s*/\s*");

static SomeTypeYouMadeToHoldCalendarDate getDate() {
  while (true) { /* Might want to give user a way to quit. */
    String line = 
      System.console().readLine("Please enter your birth date (mm / dd / yyyy): ");
    Scanner in = new Scanner(line);
    if (!in.hasNextInt())
      continue;
    int month = in.nextInt();
    if (!in.hasNext(SLASH)
      continue;
    in.next(SLASH);
    ...
    if (!validDate(month, day, year))
      continue;
    return new SomeTypeYouMadeToHoldCalendarDate(month, day, year);
  }
}

回答by Scooter

This uses Scanner methods to parse:

这使用 Scanner 方法来解析:

import java.util.Scanner;
import java.util.InputMismatchException;

public class TestScanner {

   int month, day, year;
   public static void main(String[] args)
   {
      TestScanner theApp = new TestScanner();   
      theApp.getDate();
      theApp.calcNum();
   }

   public void getDate()
   {
      int fields = 0;
      String delim1 = "";
      String delim2 = "";
      Scanner in = new Scanner(System.in);

      do
      {
         fields = 0;
         System.out.print("Please enter your birth date (mm / dd / yyyy): ");
         while ( fields < 5 && in.hasNext() )
         {
            try {
               fields++;
               switch (fields)
               {
                  case 1:
                     month = in.nextInt();
                     break;
                  case 3:
                     day = in.nextInt();
                     break;
                  case 5:
                     year = in.nextInt();
                     break;
                  case 2:
                     delim1 = in.next();
                     break;
                  case 4:
                     delim2 = in.next();
                     break;
               }
            }
            catch (InputMismatchException e)
            {
               System.out.println("ERROR: Field " + fields + " must be an integer");
               String temp = in.nextLine();
               fields = 6;
               break;
            }
         }
      } while ( fields != 5 || validDate(delim1, delim2) == false);
      in.close();
      System.out.println("Input date: " + month + "/" + day + "/" + year);
   }   

   boolean validDate(String delim1, String delim2)
   {
      if ( ( !  delim1.equals("/") ) || ( ! delim2.equals("/") ) ) 
      {
         System.out.println("ERROR: use '/' as the date delimiter");
         return false;
      }
      if ( month < 1 || month > 12 )  
      {
         System.out.println("Invalid month value: " + month);
         return false;
      }
      if (  day < 1 || day > 31 ) 
      {
         System.out.println("Invalid day value: " + day);
         return false;  
      }
      if (  year < 1 || year > 3000 ) 
      {
         System.out.println("Invalid year: " + year);
         return false;  
      }
      return true;
   }

   void calcNum()
   {

   }

}