简体   繁体   English

Java子字符串方法出现问题

[英]Issues with Java substring method

I wrote a program that prompts a user to input his/her full name First , middle , last. 我编写了一个程序,提示用户输入他/她的全名First,middle,last。 I'm attempting to break that name down into three separate pieces using the substring method by locating each white space in the string. 我试图通过找到字符串中的每个空格,使用substring方法将该名称分解为三个单独的部分。 Once each white space is found the following portion of the name is stored in a new string variable. 找到每个空格后,名称的以下部分将存储在新的字符串变量中。

The issue I'm having is that the middle name is storing both middle and last because the counter isn't stopping correctly as you will see in my below code so my question is how can I fix this. 我遇到的问题是中间名存储中间名和姓氏,因为计数器没有正确停止,正如您在下面的代码中看到的那样,所以我的问题是如何解决此问题。

Please note, I do not want to split the string, I do not want to use a StringTokenizer, I do not want to use Arrays, I already know how to do it that way. 请注意,我不想拆分字符串,我不想使用StringTokenizer,我不想使用Arrays,我已经知道该怎么做。 All I need to know is how to fix my counter, what I am trying to do will work this way I'm not looking for a new way to do this; 我所需要知道的是如何解决我的问题,我试图做的事情将以这种方式起作用,而不是寻找一种新的方式来解决此问题。 I'm only working with substring and charAt. 我只使用substring和charAt。

import java.util.Scanner;

public class Example 
{
  public static void main(String[] args)
  {
    String name = "", 
           firstName = "",
           middleName = "",
           lastName = ""; 

    Scanner in = new Scanner(System.in);       

           System.out.print("Please enter your name 'First Middle Last': "); 
           name = in.nextLine();



           int i = 0; 

  while(i < name.length())
  {   
      if(name.charAt(i) == ' ')
      {
           firstName = name.substring(0, i); // Starts at 0 ends at first occurence of ' '

         /* middleName = name.substring(i + 1, i); Should start at i + 1, 
            or one postion after the previously located white space and 
            then end at the next occurence of ' '

           ^ The above does not work, and this is where the issue is      
             happening, how ever if I do the following */

             middleName = name.substring(i + 1, name.length()); 

           /* This does work but because the endIndex is name.length() it  
               runs the length of name and grabs both the middle and last name.*/   
                     i = name.length();


             }
                ++i;
           } 



    System.out.print("\nDisplayed with last name first: " + "\nLast Name: " + lastName + "\nFisrt Name: " + firstName + "\nMiddle Name: " + middleName);

  }

}

The output this produces looks like this 产生的输出看起来像这样

Please enter your name 'First Middle Last': First Middle Last

Displayed with last name first:
Last Name:
First Name: First
Middle Name: Middle Last

As you can see first Name is displayed correctly. 如您所见,名字正确显示。 Middle name is not because it included "Last" and not just "middle" 中间名称不是因为它包含“ Last”,而不仅仅是“ Middle”

You could use indexOf(' ') and lastIndexOf(' ') to find first space and last space 您可以使用indexOf(' ')lastIndexOf(' ')查找第一个空格和最后一个空格

  • everything before 1st space is firstname 第一个空格之前的所有东西都是firstname
  • everything after last space is lastname lastname后的所有内容均为lastname
  • the rest in the middle is middlename 中间的其余部分是中间middlename

Pseudocode: 伪代码:

firstName = name.substring(0, name.indexOf(' '));
middleName = name.substring(name.indexOf(' ') + 1, name.lastIndexOf(' '));
lastName = name.substring(name.lastIndexOf(' ') + 1);

Instead of substring you can use split function: 可以使用split函数代替substring

String string = "Peter Ralph Joseph"; //Here the string
String[] parts = string.split(" "); //Here the string it is divide taking as reference the space
System.out.println(parts[0]); //Peter
System.out.println(parts[1]); //Ralph
System.out.println(parts[2]); //Joseph

In my opinion, it is easier and faster to do it with split function. 我认为,使用split功能可以更轻松,更快速地完成此操作。

Instead of running through a loop with charAt , if you really want to use substring you could just do: 如果您真的想使用substring那么可以不用执行charAt循环,而可以这样做:

int firstSpace = fullName.indexOf(' ');
String firstName = fullName.substring(0, firstSpace);

int secondSpace = fullName.indexOf(' ', firstSpace+1);
String middleName = fullName.substring(firstSpace+1, secondSpace);

String lastName = fullName.substring(secondSpace+1);
var mode = 0;
var last = 0;
for(i=0;i<name.length();i++)
{   
    if(name.charAt(i)==' '||i==(name.length()-1))
    {
       mode++;
       var text = name.substring(last, i-last);
       last = i+1;
       if(mode==1) { firstName = text; }
       else if(mode==2) { middleName = text; }
       else if(mode==3) { lastName = text; break; }
    } 
}

do it in the following way: no need to run the while loop. 通过以下方式进行操作:无需运行while循环。

firstName=name.substring(0,name.indexOf(' '));
 middleName=name.substring(name.indexOf(' ')+1,name.lastIndexOf(' '));
 lastName=name.substring(name.lastIndexOf(' ')+1,name.length());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM