如何将字符串中的特定单词更改为大写

时间:2012-02-05 06:45:09

标签: java

输入:一只快速的棕色狐狸跳过一只懒狗。 输出:一只快速的棕色狐狸跳过LAZY狗。

4 个答案:

答案 0 :(得分:2)

public class ConvertWordToUpperCase {
    public static void main(String ar[])
    {
            String inputStr = "a quick brown fox jumps over a lazy dog";
            String outputStr = "";

            String words[] = inputStr.split(" ");

            for(int i = 0; i < words.length; i++)
            {
                String word = words[i];
                if(word.equalsIgnoreCase("quick") || word.equalsIgnoreCase("lazy"))
                {
                    word = word.toUpperCase();
                }
                outputStr += word;
                outputStr += " ";
            }
            System.out.println(outputStr);
        }
    }

答案 1 :(得分:1)

Java中没有用于此目的的现成方法,但是您可以创建自己的usedefined方法,请查看以下代码。

public class ChangeWord
{
    private void upperCaseWord ( String str, String word )
    {
        if ( str.indexOf ( word ) != -1 ) // Checking the Existance of word
        {
            int strLen = str.length();
            int index = str.indexOf ( word );
            int length = word.length();
            word = word.toUpperCase();
            String part1 = str.substring ( 0 , index );
            String part2 = str.substring ( index + length );
            String finalStr = part1 + word + part2;
            System.out.println ( "Final Result : " + finalStr );
        }
    }


    public static void main ( String args[] )
    {
        ChangeWord cw = new ChangeWord();
        String str  = "a quick brown fox jumps over a lazy dog";
        cw.upperCaseWord ( str, "quick" );
    }
}

答案 2 :(得分:1)

这是一种简单的方法:

    List<String> wordsToUppercase = Arrays.asList(new String[] { "lazy",
            "quick" });

    String input = "a quick brown fox jumps over a lazy dog.";

    for (String word : wordsToUppercase) {
        input = input.replaceAll(word, word.toUpperCase());
    }

    System.out.println(input);

答案 3 :(得分:0)

.toUpperCase();会使整个字符串变为大写。如果您要查找这些特定字词,则必须使用String.format() and .subString();

的变体