gpt4 book ai didi

java - 当 charAt(i) = ' ' 时,如何防止 Java for 循环中断?

转载 作者:行者123 更新时间:2023-12-02 05:21:11 25 4
gpt4 key购买 nike

我有一个程序应该检查字符串中 # 和 @ 的数量。我的代码工作正常,但是当 for 循环到达字符串中的空格时,无明显原因就会中断。我在网上进行了广泛的查找,但在文档或其他帮助论坛中找不到有关此类问题的任何内容。问题不是代码出错,而是退出循环。

for(int i = 0; i < length; i++){
if(tweet.charAt(i) == '@' && tweet.charAt(i+1) != ' '){
attribution++;
}
else if(tweet.charAt(i) == '#' && tweet.charAt(i+1) != ' '){
hashtag++;
}
}

以下是代码运行的一些示例:

> run Main
Please enter a tweet:
#hashtag@attribution#hashtag
Length Correct
Number of Hashtags: 2
Number of Attributions: 1
Number of Links: 0
>

> run Main
Please enter a tweet:
#hashtag @attribution #hashtag
Length Correct
Number of Hashtags: 1
Number of Attributions: 0
Number of Links: 0
>

这是整个程序:

import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;

class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int hashtag = 0;
int attribution = 0;
int link = 0;
System.out.println("Please enter a tweet:");
String tweet = scan.next();
int length = tweet.length();
if(length > 140){
int excess = length - 140;
System.out.println("Excess Characters: " + excess);
}
else if(length-1 <= 140){
for(int i = 0; i < length; i++){
if(tweet.charAt(i) == '@' && tweet.charAt(i+1) != ' '){
attribution++;
}
else if(tweet.charAt(i) == '#' && tweet.charAt(i+1) != ' '){
hashtag++;
}
}
System.out.println("Length Correct\nNumber of Hashtags: " + hashtag + "\nNumber of Attributions: " + attribution + "\nNumber of Links: " + link);
}
else{
System.out.println("What the bloody hell have you done?");
}
}
}

最佳答案

@ 时,您的代码将会中断或#字符位于字符串的末尾,因为您检查 charAt(i+1)而不确保i+1小于 length .

有一种更简单的方法可以找出哈希标签的数量和 @字符串中的 s - 您所需要做的就是用空字符串替换所需的字符,并比较长度,如下所示:

String text = "...";
int numHashTags = text.length() - text.replaceAll("#(?!\\s)", "").length();
int numAttr = text.length() - text.replaceAll("@(?!\\s)", "").length();

注意 (?!\\s)的正则表达式。这些negative lookaheads防止正则表达式匹配后跟空格的符号。

关于java - 当 charAt(i) = ' ' 时,如何防止 Java for 循环中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26509568/

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