I would make a simple code in java to replace the letter 'z' by letter 'y' >>> here are the code
String s= "generalization";
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='z') s.charAt(i)='y';
The compiler return to me an error >>> why?
Strings are immutable. You can use a simple character array and alter the characters at the corresponding indices
Something like this perhaps:
String s = "Generalization";
char[] sChars = s.toCharArray();
for (int i = 0; i < sChars.length; i++) {
if (sChars[i] == 'z') {
sChars[i] = 'y';
}
}
s = String.copyValueOf(sChars);
System.out.println(s);
Prints out: Generaliyation
Or like suggested in another answer, in this sort of cases there is something called Regular expressions aka regex, with this the same thing is also accomplished by writing:
String s = "Generalization";
s = s.replace("z", "y");
System.out.println(s);
This also prints out: Generaliyation.
You can use the method replaceAll of the String class.
String s = "generalization";
s = s.replaceAll("[z]", "y");
Be careful, the first argument is a regex!
Related
For example, if I have Hello World it should become Holle Werld. How can I do this using String.replace? I've tried doing "Hello World".replace("e","o") but I only get Hollo World and if I use it again I will get Helle Werld.
You could also do:
String result = Arrays.stream(input.split(""))
.map(c -> c.equals("e") ? "o" : c.equals("o") ? "e" : c)
.collect(Collectors.joining());
Optimized Java 8 solution:
String str = "Hello World!";
String result = str.codePoints()
.map(c -> c == 'e' ? 'o' : c == 'o' ? 'e' : c)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
This solution avoids using highweight methods like String.replace, String.split and even String.equals.
I might treat the string as a character array here, and iterate over it:
String input = "Hello World";
char[] letters = input.toCharArray();
for (int i=0; i < letters.length; ++i) {
if (letters[i] == 'e') {
letters[i] = 'o';
}
else if (letters[i] == 'o') {
letters[i] = 'e';
}
}
String output = new String(letters);
System.out.println(input);
System.out.println(output);
Hello World
Holle Werld
Note that we could try doing a String#replace here, using a dummy character as a placeholder. But that runs the risk of the placeholder appearing somewhere as part of the string. The above solution would work in all cases.
Following a suggestion by #Carlos Heuberger, you can use '\uFFFF' as a placeholder to interchange the characters with each other using the String.replace() method.. '\uFFFF' is considered a non-character in Unicode (i.e., it cannot appear in a String).
String str = "Hello World";
str = str.replace('o', '\uFFFF').replace('e', 'o').replace('\uFFFF', 'e');
Hope it helps.
I'm assuming you have to use replace()
Following is one way to do it:
String input = "Hello World";
input = input.replace("e","~");
input = input.replace("o","e");
input =input.replace("~","o);
Note: This assumes String won't have "~" in it. This code isn't robust enough code to handle that scenario.
You can also find a character or a combination of characters that are not contained in your string, and use it as a temporary string of replacement. Here is an example :
private void funnyReplace2(String myString){
String unused = findUnused(myString);
System.out.println("Unused character(s) used : "+unused);
myString=myString.replace("e",unused);
myString=myString.replace("o","e");
myString=myString.replace(unused,"o");
System.out.println(myString);
}
private String findUnused(String aString){
String lookingForChar = "##{}]#$^£¨*ù%µ§/.?,;:!&é()-èïô";
int looper = 0;
while(looper<lookingForChar.length()){
looper++;
for (int i =0; i<=lookingForChar.length()-looper; i++){
if (!aString.contains(lookingForChar.substring(i,i+looper)))
return lookingForChar.substring(i,i+looper);
}
}
return "What kind of String do you have ??";
}
I am writing a cryptography program that converts the ciphertext to plaintext. By the letter's frequency, I manually crack all the cipher's letters to plaintext, and there is no patterns, so I need to write a loop that contains 26 times, to convert every single letter in the string to another letter.
My first try is using the replace statement in java,
which will be like this
str=str.replaceAll("A","E");
The question is, for instance, I input a string like this abc
and my key will be like this "replace a with c, replace b with p, replace c with q".
The output I want should be cpq, but the output I got is qpq.
Which means I want it be like one time convert.
So I am trying to use the loop, using the if
The way I am doing it is:
for (i=1;i<string.length;i++)
if (char[i]=="a")
char [i] ="b";
The error tells me that I can't convert string to char.
And also, I want to ask if I put the other 25 if statements inside this statement or pararall them?
To answer the second part of your question: I would not add 25 single if statements in your loop but instead use a Map<Character, Character> to store your replacements.
A complete solution could look like this:
public static void main(String[] args) {
Map<Character, Character> replacements = new HashMap<>();
replacements.put('a', 'c');
replacements.put('b', 'p');
replacements.put('c', 'q');
String input = "abcd";
StringBuilder output = new StringBuilder();
for (Character c : input.toCharArray()) {
output.append(replacements.getOrDefault(c, c));
}
System.out.println(output.toString());
}
This will keep characters you don't have a replacement for. Output:
cpqd
You can solve this as :
String str = "abc";
char [] ch = str.toCharArray();
for(int i=0; i<str.length(); i++){
if('a'==str.charAt(i)){
ch[i] = 'c';
}
if('b'==str.charAt(i)){
ch[i] = 'p';
}
if('c'==str.charAt(i)){
ch[i] = 'q';
}
}
System.out.println(String.valueOf(ch));
You can't convert a String to a char. So you need to either use all Strings or all chars. Instead of using the double quotes for String you could use the single quotes for char like this:
char[i]=='b'
and
char[i] = 'b';
Also instead of using a long if/else statement you could either use a switch statement, or even better you could create and use a Map to store the conversions in key/value pairs.
I have the following string:
String n = "(.........)(......)(.......)(......) etc"
I want to write a method which will fill a List<String> with every substring of n which is between ( and ) . Thank you in advance!
It can be done in one line:
String[] parts = input.replaceAll("(^.*\\()|(\\).*$)", "").split("\\)\\(");
The call to replaceAll() strips off the leasing and trailing brackets (plus any other junk characters before/after those first/last brackets), then you just split() on bracket pairs.
I'm not very familiar with the String methods, so I'm sure there's a way that it could be done without having to code it yourself, and just using some fancy method, but here you go:
Tested, works 100% perfect :)
String string = "(stack)(over)(flow)";
ArrayList<String> subStrings = new ArrayList<String>();
for(int c = 0; c < string.length(); c++) {
if(string.charAt(c) == '(') {
c++;
String newString = "";
for(;c < string.length() && string.charAt(c) != ')'; c++) {
newString += string.charAt(c);
}
subStrings.add(newString);
}
}
If the (...) pairs aren't nested, you can use a regular expression in Java. Take a look at the java.util.regex.Pattern class.
I made this regex version, but it's kind of lengthy. I'm sure it could be improved upon. (note: "n" is your input string)
Pattern p = Pattern.compile("\\((.*?)\\)");
Matcher matcher = p.matcher(n);
List<String> list = new ArrayList<String>();
while (matcher.find())
{
list.add(matcher.group(1)); // 1 == stuff between the ()'s
}
This should work:
String in = "(bla)(die)(foo)";
in = in .substring(1,in.length()-1);
String[] out = in .split(Pattern.quote(")("));
I have a Character array (not char array) and I want to convert it into a string by combining all the Characters in the array.
I have tried the following for a given Character[] a:
String s = new String(a) //given that a is a Character array
But this does not work since a is not a char array. I would appreciate any help.
Character[] a = ...
new String(ArrayUtils.toPrimitive(a));
ArrayUtils is part of Apache Commons Lang.
The most efficient way to do it is most likely this:
Character[] chars = ...
StringBuilder sb = new StringBuilder(chars.length);
for (Character c : chars)
sb.append(c.charValue());
String str = sb.toString();
Notes:
Using a StringBuilder avoids creating multiple intermediate strings.
Providing the initial size avoids reallocations.
Using charValue() avoids calling Character.toString() ...
However, I'd probably go with #Torious's elegant answer unless performance was a significant issue.
Incidentally, the JLS says that the compiler is permitted to optimize String concatenation expressions using equivalent StringBuilder code ... but it does not sanction that optimization across multiple statements. Therefore something like this:
String s = ""
for (Character c : chars) {
s += c;
}
is likely to do lots of separate concatenations, creating (and discarding) lots of intermediate strings.
Iterate and concatenate approach:
Character[] chars = {new Character('a'),new Character('b'),new Character('c')};
StringBuilder builder = new StringBuilder();
for (Character c : chars)
builder.append(c);
System.out.println(builder.toString());
Output:
abc
First convert the Character[] to char[], and use String.valueOf(char[]) to get the String as below:
char[] a1 = new char[a.length];
for(int i=0; i<a.length; i++) {
a1[i] = a[i].charValue();
}
String text = String.valueOf(a1);
System.out.println(text);
It's probably slow, but for kicks here is an ugly one-liner that is different than the other approaches -
Arrays.toString(characterArray).replaceAll(", ", "").substring(1, characterArray.length + 1);
Probably an overkill, but on Java 8 you could do this:
Character[] chars = {new Character('a'),new Character('b'),new Character('c')};
String value = Arrays.stream(chars)
.map(Object::toString)
.collect( Collectors.joining() );
At each index, call the toString method, and concatenate the result to your String s.
how about creating your own method that iterates through the list of Character array then appending each value to your new string.
Something like this.
public String convertToString(Character[] s) {
String value;
if (s == null) {
return null;
}
Int length = s.length();
for (int i = 0; i < length; i++) {
value += s[i];
}
return value;
}
Actually, if you have Guava, you can use Chars.toArray() to produce char[] then simply send that result to String.valueOf().
int length = cArray.length;
String val="";
for (int i = 0; i < length; i++)
val += cArray[i];
System.out.println("String:\t"+val);
I want to check a char variable is one of 21 specific chars, what is the shortest way I can do this?
For example:
if(symbol == ('A'|'B'|'C')){}
Doesn't seem to be working. Do I need to write it like:
if(symbol == 'A' || symbol == 'B' etc.)
If your input is a character and the characters you are checking against are mostly consecutive you could try this:
if ((symbol >= 'A' && symbol <= 'Z') || symbol == '?') {
// ...
}
However if your input is a string a more compact approach (but slower) is to use a regular expression with a character class:
if (symbol.matches("[A-Z?]")) {
// ...
}
If you have a character you'll first need to convert it to a string before you can use a regular expression:
if (Character.toString(symbol).matches("[A-Z?]")) {
// ...
}
If you know all your 21 characters in advance you can write them all as one String and then check it like this:
char wanted = 'x';
String candidates = "abcdefghij...";
boolean hit = candidates.indexOf(wanted) >= 0;
I think this is the shortest way.
The first statement you have is probably not what you want... 'A'|'B'|'C' is actually doing bitwise operation :)
Your second statement is correct, but you will have 21 ORs.
If the 21 characters are "consecutive" the above solutions is fine.
If not you can pre-compute a hash set of valid characters and do something like
if (validCharHashSet.contains(symbol))...
you can use this:
if ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(String.valueOf(yourChar)))
note that you do not need to create a separate String with the letters A-Z.
It might be clearer written as a switch statement with fall through e.g.
switch (symbol){
case 'A':
case 'B':
// Do stuff
break;
default:
}
If you have specific chars should be:
Collection<Character> specificChars = Arrays.asList('A', 'D', 'E'); // more chars
char symbol = 'Y';
System.out.println(specificChars.contains(symbol)); // false
symbol = 'A';
System.out.println(specificChars.contains(symbol)); // true
Using Guava:
if (CharMatcher.anyOf("ABC...").matches(symbol)) { ... }
Or if many of those characters are a range, such as "A" to "U" but some aren't:
CharMatcher.inRange('A', 'U').or(CharMatcher.anyOf("1379"))
You can also declare this as a static final field so the matcher doesn't have to be created each time.
private static final CharMatcher MATCHER = CharMatcher.anyOf("ABC...");
Option 2 will work. You could also use a Set<Character> or
char[] myCharSet = new char[] {'A', 'B', 'C', ...};
Arrays.sort(myCharSet);
if (Arrays.binarySearch(myCharSet, symbol) >= 0) { ... }
You can solve this easily by using the String.indexOf(char) method which returns -1 if the char is not in the String.
String candidates = "ABCDEFGHIJK";
if(candidates.indexOf(symbol) != -1){
//character in list of candidates
}
Yes, you need to write it like your second line. Java doesn't have the python style syntactic sugar of your first line.
Alternatively you could put your valid values into an array and check for the existence of symbol in the array.
pseudocode as I haven't got a java sdk on me:
Char candidates = new Char[] { 'A', 'B', ... 'G' };
foreach(Char c in candidates)
{
if (symbol == c) { return true; }
}
return false;
One way to do it using a List<Character> constructed using overloaded convenience factory methods in java9 is as :
if(List.of('A','B','C','D','E').contains(symbol) {
// do something
}
You can just write your chars as Strings and use the equals method.
For Example:
String firstChar = "A";
String secondChar = "B";
String thirdChar = "C";
if (firstChar.equalsIgnoreCase(secondChar) ||
(firstChar.equalsIgnoreCase(thirdChar))) // As many equals as you want
{
System.out.println(firstChar + " is the same as " + secondChar);
} else {
System.out.println(firstChar + " is different than " + secondChar);
}