0
点赞
收藏
分享

微信扫一扫

80题通关Java基础:第72题

就是耍帅 2022-04-05 阅读 22
javaeclipse

目录

第72题 删除字符串中多余空格(10分)

🍋题目描述

时间限制:1 秒 内存限制:32 兆
题目描述:
输入一个由若干单词组成的字符串(长度小于等于2000),然后删除字符串的首尾空格,如果串中有多于一个以上空格,则只保留一个空格。
输入:
测试数据有多组,每组输入一个字符串。
输出:
对于每组输入,删除字符串中多余空格,然后输出。

样例输入:
3
word many word
abcd xyz
xyz
样例输出:
word many word
abcd xyz
xyz
Hello!

🍋源代码

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		in.nextLine();
		for (int i = 0; i < n; i++) {
			char[] c = new char[2005];
			String s = in.nextLine();
			String s1 = s.trim();
			c = s1.toCharArray();
			String ans = "";
			for (int j = 0; j < c.length - 1; j++) {
				if (c[j] != ' ') {
					ans += c[j];
				} else if (c[j + 1] != ' ') {
					ans += c[j];
				}
			}
			ans += c[c.length - 1];
			System.out.println(ans);
		}
		in.close();
	}
}

在这里插入图片描述

举报

相关推荐

0 条评论