替换String中的单个字符 [英] Replacing a single character in a String

查看:157
本文介绍了替换String中的单个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是需要替换给定字符串中的单个字符,同时保持字符串中的其他字符。

The issue is needing to replace a single character in a given string while maintaining the other characters in the string.

代码为:

    if(command.equalsIgnoreCase("replace single"))
    {
        System.out.println("Enter the character to replace");
        String char2replace = keyboard.nextLine();
        System.out.println("Enter the new character");
        String secondChar = keyboard.nextLine();    
        System.out.println("Which " + char2replace + " would you like to replace?");
        int num2replace = keyboard.nextInt();

            for(int i=0; i< bLength; i++)
            {   

                if(baseString.charAt(i)== char2replace.charAt(0))
                {
                    baseString = baseString.substring(0, i) +
                            secondChar + baseString.substring(i + 1);

                }


推荐答案

你几乎做到了,只需在你的循环中添加一个计数器:

You almost did it, just add a counter in your loop:

int num2replace = keyboard.nextInt();
int count = 0;
for (int i = 0; i < bLength; i++) {
    if (baseString.charAt(i) == char2replace.charAt(0)) {
        count++;
        if (count == num2replace){
            baseString = baseString.substring(0, i) +
                    secondChar + baseString.substring(i + 1);
            break;
        }
    }
    if (char2replace.length() > 1) {//you need move this out of loop
        System.out.println("Error you can only enter one character");
    }


}
System.out.println(baseString);

这篇关于替换String中的单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆