计算第一个和最后一个之间的字母 - Java

时间:2014-03-04 21:55:55

标签: java

好的,所以我正在做这个项目,要求我有一个字符串的第一个和最后一个setter出现,它们之间的字母数量和输出。我已经尝试重新调整一些反向的字符串代码,我很方便,但我不能让输出出现在我的IDE中。

任何人都可以查看我的代码并提出一些建议吗?

public static void main(String[] args) {
    String countWord;
    countWord = JOptionPane.showInputDialog(null,
            "Enter the string you wish to have formatted:");
}

static String countMe(String countWord) {
    int count = 1;
    char first = countWord.charAt (0);
    char last = countWord.charAt(-1);
    StringBuilder word = new StringBuilder();
    for(int i = countWord.length() - 1; i >= 0; --i)
        if (countWord.charAt(i) != first ) {
            if (countWord.charAt(i) != last) {
                count++;
            }
        }
        return countWord + first + count + last;
    }
}

4 个答案:

答案 0 :(得分:2)

只需使用charAt()构建它:

return "" + str.charAt(0) + (str.length() - 2) + str.charAt(str.length() - 1);

前面的""会使后面的数值连接成字符串(而不是以算术方式添加)。


略微更简洁的替代方案是:

return countWord.replaceAll("(.).*(.)", "$1" + (str.length() - 2) + "$2")

答案 1 :(得分:1)

一旦确定了第一个和最后一个字符,就不需要不必要的条件。试试这个:

static String countMe(String countWord) {

char first = countWord.charAt(0);
char last = countWord.charAt(countWord.length()-1);

int count=0;

for (int i = 1; i < countWord.length()-1; i++)
    {
        count++;
    }
    return first + String.valueOf(count) + last;
    }

或者,如果不是强制使用for循环,你可以简单地将其设为

static String countMe(String countWord) {
char first = countWord.charAt(0);
char last = countWord.charAt(countWord.length()-1);

int count = countWord.substring(1, countWord.length()-1).length();

return first + String.valueOf(count) + last;
}

答案 2 :(得分:0)

您可以使用string.length()方法获取字符串的总长度。您的代码将类似于:

int totalLength = countWord.length();
int betweenLength = totalLength - 2; // This gives the count of characters between first and last letters
char first = countWord.charAt(0);
char last = countWord.charAt(str.length() - 1);
String answer = first + betweenLength + last;

答案 3 :(得分:0)

import javax.swing.JOptionPane;

public class Main{

    public static void main(String[] args) {
        String countWord;
        countWord = JOptionPane.showInputDialog(null,
                "Enter the word you wish to have formatted:");
        JOptionPane.showMessageDialog(null, countMe(countWord));
    }

    static String countMe(String countWord) {
        int count = 0;
        String first = String.valueOf(countWord.charAt(0));
        String last = String.valueOf(countWord.charAt(countWord.length() - 1));
        for(int i = 1; i < countWord.length() - 1; i++) {
            if (String.valueOf(countWord.charAt(i)) != first ) {
                count++;
            }
        }
        return first + count + last;
    }
}