gpt4 book ai didi

java 如何分隔字符串中的单词并将每个单独的单词存储在变量中

转载 作者:行者123 更新时间:2023-12-01 14:04:37 25 4
gpt4 key购买 nike

我需要将扫描仪输入分解为单独的单词或出现空格的位置。我有它在某种程度上工作,但是如果该行有太多或太少的单词,我就无法让它工作。请帮我。我有一个星期一的截止日期。这是我当前的代码。

//import java.util.Scanner;
public class durodyne {

public static void main(String[] args) {
String name;
String part1;
String remain1;
String part2;
String part3;
String part4;
String part5;
String part6;
String part7;



Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Full Product Name");
name = keyboard.nextLine();

int space=name.indexOf(' ');

part1 = name.substring(0, space);

int space2 = name.indexOf(' ', space + 1);
int space3 = name.indexOf(' ', space2 + 1);

part2 = name.substring(space, space2);

int space4 = name.indexOf(' ', space3 + 1);
int space5 = name.indexOf(' ', space4 + 1);


part3 = name.substring(space2, space3);

int space6 = name.indexOf(' ', space5 + 1);
int space7 = name.indexOf(' ', space6 + 1);


part4 = name.substring(space3, space4);


part5 = name.substring(space4, space5);

part6 = name.substring(space5, space6);

part7 = name.substring(space6, space7);]

}

最佳答案

//your initialization 
List<String> names = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Full Product Name");
name = keyboard.nextLine();
names = Arrays.asList(name.split(" "));
//your code

关于java 如何分隔字符串中的单词并将每个单独的单词存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19018084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com