gpt4 book ai didi

java - 从用户输入字符串中删除空格

转载 作者:行者123 更新时间:2023-11-29 07:31:05 24 4
gpt4 key购买 nike

我正在尝试创建一个代码来删除用户输入字符串中的空格,但我在第 16 行收到错误。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15 at practice5.main(practice5.java:16)

注意:我们不允许使用Java的replace方法。我需要手动编码。

这是我的代码:

import java.util.Scanner;

public class practice5{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
String line;
System.out.print("Sentence: ");
line = scanner.nextLine();
char phrase[] = line.toCharArray();
int i = 0;
int n = 0;

while(phrase[i] != '\0') {
if(phrase[i] == ' ') {
for(n=i; n<phrase.length; n++) {
phrase[n] = phrase[n+1];
}
}
i++;
}

String output = new String(phrase);
System.out.print(output);
}
}

谢谢!

最佳答案

您可以使用 String 类的函数。只需使用 line.replace("","")

关于java - 从用户输入字符串中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42579700/

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