package main;
import java.util.Arrays;
import javax.swing.*;
public class TweetTester {
public static void main(String[] args)
{
String tweet= JOptionPane.showInputDialog("Please enter a tweet:\n(Hashtags should be represented as #hashtags and mentions should be represented by @mentions)");
int length = tweet.length();
if (length<=140)
{
String[] splited = tweet.split("\\b+"); //split on space
if(Arrays.asList(splited).contains("#"))
{
int index = tweet.indexOf("#");
int count = 0;
while (index != -1)
{
count++;
tweet = tweet.substring(index + 1);
index = tweet.indexOf("#");
}
System.out.println("No of *#* in the input is : " + count);
}
if(Arrays.asList(splited).contains("@"))
{
int index = tweet.indexOf("@");
int count2 = 0;
while (index != -1)
{
count2++;
tweet = tweet.substring(index + 1);
index = tweet.indexOf("@");
}
System.out.println("No of *@* in the input is : " + count2);
}
if(Arrays.asList(splited).contains("http://"))
{
int index = tweet.indexOf("http://");
int count3 = 0;
while (index != -1)
{
count3++;
tweet = tweet.substring(index + 1);
index = tweet.indexOf("http://");
}
System.out.println("No of *http://* in the input is : " + count3);
}
//JOptionPane.showMessageDialog(null, (140 - length)+" Charcters Left\n"+"Tweet:\n"+tweet+"\nLength Correct"+ "number of #:"+count);
}
if (length>140 ){
JOptionPane.showMessageDialog(null,"Excess Characters: "+(length-140));
}
}
}
答案 0 :(得分:1)
首先,您可能应该使用\\s+
regexp:
String[] splited = tweet.split("\\s+"); //split on space
其次,在每个if(){...}中,您修改(截断)您的原始推文字符串并丢失一些数据。
例如,当你的推文等于:
String tweet = "one @ two # # three # four";
你的第一个if()删除了origianl tweet字符串的第一部分:
tweet = tweet.substring(index + 1);
并且在第二个if()推文中没有任何"@"
个字符。
上述推文的结果是:
No of *#* in the input is : 3
No of *@* in the input is : 0
答案 1 :(得分:0)
你改变了推文。这是不需要的,因为有一个String.indexOf(String seek,int startPos)。 更好的是,不要重复自己:
public static int count(String sentence, String word) {
int count = 0;
int oldPos = 0;
for (;;) {
int pos = sentence.indexOf(word, oldPos);
if (pos == -1) {
break;
}
count++;
oldPos = pos + word.length();
}
return count;
}
正则表达式"\\b"
用于字边界,对http://
有问题。
实际上,为什么不简单计数,然后测试计数!= 0。
public static void main(String[] args)
{
String tweet= JOptionPane.showInputDialog("Please enter a tweet:\n"
+ "(Hashtags should be represented as #hashtags and mentions should be "
+ "represented by @mentions)");
int length = tweet.length();
if (length<=140)
{
int count = count(tweet, "#");
if (count > 0) {
System.out.println("No of *#* in the input is : " + count);
}
count = count(tweet, "@");
if (count > 0) {
System.out.println("No of *@* in the input is : " + count);
}
count = count(tweet, "http://");
if (count > 0) {
System.out.println("No of *http://* in the input is : " + count);
}
}
else
{
JOptionPane.showMessageDialog(null,"Excess Characters: " + (length-140));
}