简体   繁体   English

用与同一索引不同的字符替换特定的索引字符

[英]replace specific index character with different character from same index

I'm still very new java and find that I spend a lot of time spinning my wheels for things that may be simple. 我还是Java的新手,发现我花了很多时间来做一些可能很简单的事情。 I am writing an app that takes a user entered string of text and places it into a charArray. 我正在编写一个应用程序,它将用户输入的文本字符串放入到charArray中。 From here, I want to use the replace method to replace the character at index 0 with the character at index 1. ( I understand that replace will change all other values in the string that have the same value as char(0). 从这里开始,我想使用replace方法将索引0处的字符替换为索引1处的字符。(我知道replace会更改字符串中与char(0)相同的所有其他值。

if (input.equals(blank) || input.equals(mptee)){   
    System.out.println("You have choen to exit, Goodbye");
}

char[] stringToCharArray = input.toCharArray(); // convert string to charArray

for(char output : stringToCharArray) {
    System.out.print(output);
    //code to simplify character validation    
    Character x = input.charAt(0);       
    Character y = input.charAt(1);                  
    if( Character.isLetter(input.indexOf(0)) 
                        && ( Character.isLetter(input.indexOf(1))) ){
        input.replace(input.charAt(0),input.charAt(1));
    }
}
System.out.println(input);

Although it accepts a string, and gives the length, the character replace does not occur. 尽管它接受字符串并给出长度,但是不会发生字符替换。 I have read for days on "indexOf" , String RegEx, and much more. 我已经阅读了几天的“ indexOf”,String RegEx等内容。 Any assistance would be appreciated. 任何援助将不胜感激。

Strings are immutable so after you call the replace method you need to assign it back to input . 字符串是不可变的,因此在调用replace方法之后,需要将其分配回input Change 更改

input.replace(input.charAt(0),input.charAt(1));

to

input  = input.replace(input.charAt(0),input.charAt(1));
String input = new String("abcdefgh");
input = input.substring(1, 2) + input.substring(1);

gives you bbcdefgh if that is what you want? 给你bbcdefgh如果那是你想要的?

Is it a must to convert the string to a char array and go through the for loop? 将字符串转换为char数组并通过for循环是否必须?
I find it a bit unnecessary since you are only working on the first & second character. 我发现它有点多余,因为您仅在处理第一个和第二个字符。

If you must convert it to a char array, what about this? 如果必须将其转换为char数组,该怎么办?

String input = new String("abcdefgh");      
char[] stringToCharArray = input.toCharArray();

if(Character.isLetter(stringToCharArray[0]) && Character.isLetter(stringToCharArray[1]))
{
    // Replace character at index 0 with character at index 1
    stringToCharArray[0] = stringToCharArray[1];
}

input = String.valueOf(stringToCharArray); // Convert back to String
System.out.println(input); // Gives you bbcdefgh

There is more than 1 way to achieve what you want, so maybe you can take a look at the String documentation? 有多种方法可以实现所需的功能,因此也许您可以看一下String文档?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM