使用Java对字符串中的单词进行拆分和大写

使用Java对字符串中的单词进行拆分和大写,java,string,Java,String,我正在为一项作业写一个方法 描述:如果字符串包含包含大写字母的单词,则我的方法需要将整个单词大写 所以“hello StackOverFlow,我的名字是John”将产生“hello StackOverFlow,我的名字是John” 我的代码: /*Helper method for capitalizeWords() capitalizes word if necesarry*/ private static String capitalizeWord(String s, int positi

我正在为一项作业写一个方法

描述:如果字符串包含包含大写字母的单词,则我的方法需要将整个单词大写

所以“hello StackOverFlow,我的名字是John”将产生“hello StackOverFlow,我的名字是John”

我的代码:

/*Helper method for capitalizeWords() capitalizes word if necesarry*/
private static String capitalizeWord(String s, int position) {
    int i = position;
    String word = "";
    String testWord = "";

    while (s.charAt(i) != ' ' && i < s.length() - 1) {
        word += s.charAt(i);
        i++;
    }
    word += " ";
    testWord = word.toLowerCase();
    if (!testWord.equals(word)) {
        word = word.toUpperCase();
    }
    return word;
}

public static String capitalizeWords(String s) {
    StringBuilder newString = new StringBuilder();
    if (s.length() == 1) {
        newString.append(s.charAt(0));
        return newString.toString();
    }

    for (int i = 0; i < s.length(); i++) {
        if (i == 0) {
            newString.append(capitalizeWord(s, i));
        } else if (s.charAt(i) == ' ') {
            newString.append(capitalizeWord(s, i + 1));
        }
    }
    return newString.toString();
}
如果不手动添加最后一个字符,我想不出一种方法来解决这个问题,这可能会在这个作业中被扣分。我宁愿学习正确、有效的方法来解决这个问题(考虑到允许的方法),也不愿努力想出一个粗糙的解决方案


你们谁介意给我一些想法吗?我无法使用
子字符串
索引

关于跳过最后一个字符,请检查while循环:

while(s.charAt(i) != ' ' && i <s.length()-1)
{
    word += s.charAt(i);
    i++;
}

while(s.charAt(i)!=”&&i关于跳过最后一个字符,请检查while循环:

while(s.charAt(i) != ' ' && i <s.length()-1)
{
    word += s.charAt(i);
    i++;
}

while(s.charAt(i)!=”&&i你实际上非常接近。你需要做两个改变

首先,您在循环中迭代的字符太少。您希望一直到
i
,而不是
s.length()-1

但是,如果您只是进行了更改,那么您将遇到
s.charAt(i)
语句的问题,因为
i
将在下一个循环中超出范围

要避开这个问题,请翻转您的
&&

while (i < s.length() && s.charAt(i) != ' ') {
    word += s.charAt(i);
    i++;
}
while(i

由于
&&
短路,如果
i>=s.length()

实际上非常接近,则不会计算第二部分。需要进行两个更改

首先,您在循环中迭代的字符太少。您希望一直到
i
,而不是
s.length()-1

但是,如果您只是进行了更改,那么您将遇到
s.charAt(i)
语句的问题,因为
i
将在下一个循环中超出范围

要避开这个问题,请翻转您的
&&

while (i < s.length() && s.charAt(i) != ' ') {
    word += s.charAt(i);
    i++;
}
while(i

由于
&&
短路,如果
i>=s.length()

您可以简化代码并利用
字符中的实用方法(如and)。我还建议使用。然后您可以在适当的位置构建单个单词。例如

public static String capitalizeWords(String s) {
    StringBuilder sb = new StringBuilder();
    StringBuilder word = new StringBuilder();
    boolean capital = false;
    for (char ch : s.toCharArray()) {
        if (Character.isWhitespace(ch)) {
            if (word.length() > 0) {
                sb.append(capital ? word.toString().toUpperCase() : word);
                word.setLength(0);
                capital = false;
            }
            sb.append(ch);
            continue;
        } else if (Character.isUpperCase(ch)) {
            capital = true;
        }
        word.append(ch);
    }
    if (word.length() > 0) {
        sb.append(capital ? word.toString().toUpperCase() : word);
    }
    return sb.toString();
}
我用它做了测试

System.out.println(capitalizeWords("Guess what??  There are twenty-sIx letters "
    + "in the English alphABEt!"));
System.out.println(capitalizeWords("hello StackOverFlow, my name is John"));
获得(预期的)


您可以简化代码并利用
Character
中的实用方法(例如and)。我还建议使用。然后您可以在适当的位置构建单个单词。例如

public static String capitalizeWords(String s) {
    StringBuilder sb = new StringBuilder();
    StringBuilder word = new StringBuilder();
    boolean capital = false;
    for (char ch : s.toCharArray()) {
        if (Character.isWhitespace(ch)) {
            if (word.length() > 0) {
                sb.append(capital ? word.toString().toUpperCase() : word);
                word.setLength(0);
                capital = false;
            }
            sb.append(ch);
            continue;
        } else if (Character.isUpperCase(ch)) {
            capital = true;
        }
        word.append(ch);
    }
    if (word.length() > 0) {
        sb.append(capital ? word.toString().toUpperCase() : word);
    }
    return sb.toString();
}
我用它做了测试

System.out.println(capitalizeWords("Guess what??  There are twenty-sIx letters "
    + "in the English alphABEt!"));
System.out.println(capitalizeWords("hello StackOverFlow, my name is John"));
获得(预期的)


我相信以下代码可以帮助您完成任务

public String capitalize(String sentence) {
    String[] words = sentence.split(" ");
    for (int i = 0; i < words.length; ++i) {
        String word = words[i];
        for (int j = 0; j < word.length(); ++j) {
            if (Character.isUpperCase(word.charAt(j))) {
                words[i] = words[i].toUpperCase();
                break;
            }
        }
    }
    StringBuffer result = new StringBuffer();
    for (String word : words) {
        result.append(word).append(" ");
    }
    return result.toString();
}
公共字符串大写(字符串句子){
字符串[]单词=句子。拆分(“”);
for(int i=0;i
我相信以下代码可以帮助您完成任务

public String capitalize(String sentence) {
    String[] words = sentence.split(" ");
    for (int i = 0; i < words.length; ++i) {
        String word = words[i];
        for (int j = 0; j < word.length(); ++j) {
            if (Character.isUpperCase(word.charAt(j))) {
                words[i] = words[i].toUpperCase();
                break;
            }
        }
    }
    StringBuffer result = new StringBuffer();
    for (String word : words) {
        result.append(word).append(" ");
    }
    return result.toString();
}
公共字符串大写(字符串句子){
字符串[]单词=句子。拆分(“”);
for(int i=0;i
我想看看如何使用.split方法,并提供一个空格作为参数。请参见:是,首先使用string.split或StringTokenizer拆分字符串中的单词。然后,您可以检查每个单词的第一个字符,以决定是否必须大写。@hotzst不一定是第一个,任何字符。@Tunaki right,我的结束语我很想使用split()但不允许。我会考虑使用.split方法,并提供一个空格作为参数。请参见:是,从使用string.split或StringTokenizer拆分字符串中的单词开始。然后您可以检查每个单词的第一个字符,以决定是否必须大写。@hotzst不一定是第一个,任何字符。@Tunaki ri好的,我的疏忽我很想使用split(),但不允许使用。如果您只这样做,您将获得一个
StringIndexOutOfBoundsException
。当我看到您的答案时,我正要将其添加进来:)我以前尝试过此操作,但收到以下错误。java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:67As@Makoto说,您需要交换
&
语句的两半以避免此错误。很抱歉,我刚才看到了Makaot的注释。如何更改其余代码以避免此错误?您将获得e> StringIndexOutOfBoundsException
如果你这样做的话。我正要添加它,这时我看到了你的答案:)我以前尝试过这个,但收到了以下错误。java.lang.StringIndexOutOfBoundsException:String索引超出范围:67As@Makoto说,您需要交换
&&
语句的两部分以避免此错误。很抱歉,我刚才看到了Makaot的评论。我如何更改代码的其余部分以避免此错误?谢谢,我很感激!谢谢你,我很感激!我真的很感激这个解决方案。不幸的是,我们不允许在循环中使用“continue”。此外,我们不允许使用数组。我的公关