Wrong Answer with Java - java

I'm a student that is learning Java, and I have this code:
lletres = lletres.replace(lletres.charAt(2), codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres is a string, and it's like this
lletres = "BBB"
The result is "CCC" and I only want to change the last B, so the result can be like this: "BBC".

Reading the documentation for String.replace should explain what happened here (I marked the relevant part in bold):
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
One way to solve it is to break the string up to the parts you want and then put it back together again. E.g.:
lletres = lletres.substring(0, 2) + (char)(lletres.charAt(2) + 1);

As others pointed replace() will replace all the occurrences which matched.
So, instead you can make use of replaceFirst() which will accept the regx
lletres = lletres.replaceFirst( lletres.charAt( 2 ) + "$", (char) ( lletres.charAt( 2 ) + 1 ) + "" )

You could use StringBuilder for your purpose:
String lletres = "BBB";
String codi = "CCC";
StringBuilder sb = new StringBuilder(lletres);
sb.setCharAt(2, codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres = sb.toString();

If you need to change only the last occurrence in the string, you need to split the string into parts first. I hope following snippet will be helpful to you.
String lletres = "BBB";
int lastIndex = lletres.lastIndexOf('B');
lletres = lletres.substring(0, lastIndex) + 'C' + lletres.substring(lastIndex+1);
This code will find index of last letter B and stores it in lastIndex. Then it splits the string and replaces that B letter with C letter.
Please keep in mind that this snippet doesn't check whether or not the letter B is present in the string.
With slight modification you can get it to replace whole parts of the string, not only letters. :)

Try this one.
class Rplce
{
public static void main(String[] args)
{
String codi = "CCC";
String lletres = "BBB";
int char_no_to_be_replaced = 2;
lletres = lletres.substring(0,char_no_to_be_replaced ) + codi.charAt(codi.indexOf(lletres.charAt(char_no_to_be_replaced )) + 1) + lletres.substring(char_no_to_be_replaced + 1);
System.out.println(lletres);
}
}

use this to replace the last character
lletres = lletres.replaceAll(".{1}$", String.valueOf((char) (lletres.charAt(2) + 1)));

suppose you have dynamic value at last index and you want to replace that value will increasing one then use this code
String lletres = "BBB";
int atIndex = lletres.lastIndexOf('B');
char ReplacementChar = (char)(lletres.charAt(lletres.lastIndexOf('B'))+1);
lletres= lletres.substring(0, atIndex)+ReplacementChar;
System.out.println(lletres);
output
BBC

Related

Replace characters and keep only one of these characters

Can someone help me here? I dont understand where's the problem...
I need check if a String have more than 1 char like 'a', if so i need replace all 'a' for a empty space, but i still want only one 'a'.
String text = "aaaasomethingsomethingaaaa";
for (char c: text.toCharArray()) {
if (c == 'a') {
count_A++;//8
if (count_A > 1) {//yes
//app crash at this point
do {
text.replace("a", "");
} while (count_A != 1);
}
}
}
the application stops working when it enters the while loop. Any suggestion? Thank you very much!
If you want to replace every a in the string except for the last one then you may try the following regex option:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", " ");
somethingsomething a
Demo
Edit:
If you really want to remove every a except for the last one, then use this:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", "");
You can also do it like
String str = new String ("asomethingsomethingaaaa");
int firstIndex = str.indexOf("a");
firstIndex++;
String firstPart = str.substring(0, firstIndex);
String secondPart = str.substring(firstIndex);
System.out.println(firstPart + secondPart.replace("a", ""));
Maybe I'm wrong here but I have a feeling your talking about runs of any single character within a string. If this is the case then you can just use a little method like this:
public String removeCharacterRuns(String inputString) {
return inputString.replaceAll("([a-zA-Z])\\1{2,}", "$1");
}
To use this method:
String text = "aaaasomethingsomethingaaaa";
System.out.println(removeCharacterRuns(text));
The console output is:
asomethingsomethinga
Or perhaps even:
String text = "FFFFFFFourrrrrrrrrrrty TTTTTwwwwwwooo --> is the answer to: "
+ "The Meeeeeaniiiing of liiiiife, The UUUniveeeerse and "
+ "Evvvvverything.";
System.out.println(removeCharacterRuns(text));
The console output is........
Fourty Two --> is the answer to: The Meaning of life, The Universe and Everything.
The Regular Expression used within the provided removeCharacterRuns() method was actually borrowed from the answers provided within this SO Post.
Regular Expression Explanation:

Java - Simplest way to get characters that come after substring inside string

How can I get a list of characters in a string that come after a substring? Is there a built-in String method for doing this?
List<String> characters = new ArrayList<>();
String string = "Grid X: 32";
// How can I get the characters that come after "Grid X: "?
I know you could do this with a loop, but is there another way that may be simpler?
Just grab the characters after the ": "
String string = "Grid X: 32"
int indexOFColon = string.indexOf(":");
String endNumber = string.subString(indexOFColon + 2);
So you get the index of the colon, which is 6 in this case, and then grab the substring starting 2 after that, which is where your number starts.
There are two possibilities:
Use a regular expression (regex):
Matcher m = Pattern.compile("Grid X: (\\d+)");
if (m.matches(string))
{
int gridX = Integer.parseInt(m.group(1));
doSomethingWith(gridX);
}
Use the substring method of the string:
int gridX = Integer.parseInt(string.substring(string.indexOf(':')+1).trim());
doSomethingWith(gridX);
Below code can be used for getting list of chacters :-
String gridString = "Grid X: 32";
String newString = gridString.subSubString(gridString.indexOf(gridString ) + gridString .length );
char[] charArray = newString.toCharArray();
Set nodup = new HashSet();
for(char cLoop : charArray){
nodup.add(cLoop);
}
There is more than one way to get this done. The simplest is probably just substring. But it is fraught with danger if the string doesn't actually start with "Grid X: "...
String thirtyTwo = string.substring( s.indexOf("Grid X: ") + "Grid X: ".length() );
Regex is pretty good at this too.

Check String for Uppercase letter and find position

I need to check if in my String "sir" i have some uppercase letters, if so, i need to assign the value of that letter to another string and then to delete the letter. my first part looks like this:
Pattern p = Pattern.compile("[^A-Z]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(sir);
boolean b = m.find();
so that i check if there is any uppercase letter, then i need to add assigning & deleting. i am not sure if this works. also i found
another way:
StringTokenizer stringTokenizer = new StringTokenizer(sir);
while (stringTokenizer.hasMoreTokens()) {
String a = stringTokenizer.nextToken();
if(a.equals(a.toUpperCase())) {
upper = a;
}
}
upper returns null everytime, even though sir = cL
does anyone know a way to:
get uppercase letter & positon from string
delete it
any help would be much appreciated.
To remove all UPPERCASE letters from a string:
String repl = sir.replaceAll("[A-Z]+", "");
To copy all UPPERCASE letters from a string to another string:
String upper = sir.replaceAll("[^A-Z]+", "");
This will give you all the capital letters in a string:
String inputString;
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
ouptutString += Character.isUpperCase(c) ? c + " " : "";
}
You can also try "guava" libriaries. There you can find set of classes for string manipulation. Among them CharMatcher (https://code.google.com/p/guava-libraries/wiki/StringsExplained#CharMatcher)
simple code example can be:
String string = "ABcdEFgh45";
String withoutUpperCase = CharMatcher.JAVA_UPPER_CASE.removeFrom(string);
//returns cdgh45

Character swapping

I'm trying to swap the first and last character in a string so what I did was I was able to retrieve its first and last characters but am now having hard times putting them all together:
String name="pera";
char[] c = name.toCharArray();
char first = c[0];
char last = c[c.length-1];
name.replace(first, last);
name.replace(last, first);
System.out.println(name);
Although I am getting for the variable 'first' the value of "p" and for the variable 'last' the value of "a", these methods replace() are not turning up with a valid result as the name stays as it is. Does anyone have any idea on how to finish this?
1) String are immutable in Java. so name.replace(first, last) will not modify name but will return a new String.
2) String#replace(char oldChar, char newChar) replaces all occurrences of oldChar in this string with newChar.
For example:
System.out.println("aaaddd".replace("a","d"));
Will give :
dddddd
Possible solution : If you convert your String to a char[], you can easily swap the characters :
public static String inverseFirstAndLast(String str){
char[] c = str.toCharArray();
Character temp = c[0];
c[0] = c[c.length-1];
c[c.length-1]=temp;
return new String(c);
}
Swapping the first with the last is easy like this:
String str = "SwapDemo";
String swapped = str.charAt(str.length() - 1) + str.substring(1, str.length() - 1) + str.charAt(0);
The method you tried will replace all the occurrences of the passed argument, which is not what you want. The code above will do what you want.
As Arnoud pointed out, strings are immutable. But, fixing that issue, you will still get wrong results for:
acbbc
for example
c[0] = last;
c[c.length-1] = first;
System.out.println(new String(c));
Here's a regex based solution:
String str = "demo";
String swapped = str.replaceAll("^(.)(.*)(.)$", "$3$2$1");
Related to solution of #Martijn Courteaux. You can also store the result inside same str String hence saving a little bit of space, like this:
String str = "pera";
String str = str.charAt(str.length() - 1) + str.substring(1, str.length() - 1) + str.charAt(0);

How can I split two digit into two different strings?

I have month in, which contains a value such as 12. I am trying to split it into two different strings e.g. a=1 and b=2. How do I do this?
There are several ways to do this.
// Working with Strings ------
String str = "12";
// Get char array
char[] chars = str.toCharArray();
// Two substrings
String firstStr = str.substring(0,1);
String secondStr = str.substring(1,2);
// Working with ints ---------
int i = 12;
int firstInt = i / 10; // Divide
int secondInt = i % 10; // Modulo
Use String.charAt(index) method to return a character and use Character.toString(char) to convert it to String.
Simplest way might be to convert it to a String and then use charAt() to read the characters one by one.
Sounds like a homework question :)
String x = "12";
String[] x_arr= x.split("");
your chars will be located in
x[1]
x[2]
and eventually you can go on with the index if you passed a longer string (like a year).
Just avoid x[0] because it is an empty string.
String splits[] = "12".split("#?") would work.
Use :
str.split("\\w.+")
For Example :
String[] parts = "12".split("\\w.+");
String a = parts[0]
Strign b = parts[1]
You can Take a look here
http://www.roseindia.net/regularexpressions/splitting-string.shtml
Try this:
String input = "12";
System.out.println(input.charAt(0)); // gives '1'
System.out.println(input.charAt(1)); // gives '2'
Furthermore, if you wish to have '1' and '2' as Strings (not as chars), you can do this :
String firstDigit = input.charAt(0) + "";
String secondDigit = input.charAt(1) + "";
Good luck !
Konstantin
EDIT: Lets assume that 'month' is variable of type java.util.Date. Then:
String monthToString = new SimpleDateFormat("MM").format(month);
String firstDigit = monthToString.charAt(0) + "";
String secondDigit = monthToString.charAt(1) + "";
You can use the method substring of class String.
There is the documentation: http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#substring(int, int)
The algorithm is not complex ;)

Categories

Resources