d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Android Studio > Beginner
Add Reply New Topic New Poll
Member
Posts: 1,566
Joined: Jul 6 2008
Gold: 7,051.00
Sep 8 2017 05:49pm
I have a seemingly simple problem that I just can't seem to figure out.

I am taking a string input from the user and replacing the letter x with the letter y and y with x. So for example the sentence:

"Sally likes sax."
would now be
"Sallx likes say."

Would something like this work or would it just replace the letters then replace again?

EditText et = (EditText) findViewById(R.id.textReplace);
String newText = et.getText().toString();
str= str.replace("x","y");
str= str.replace("y","x");
et.setText(str);
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Sep 8 2017 07:17pm
Quote
would it just replace the letters then replace again?

essentially all the y will become x

This post was edited by carteblanche on Sep 8 2017 07:19pm
Member
Posts: 1,566
Joined: Jul 6 2008
Gold: 7,051.00
Sep 8 2017 07:18pm
Thought so. I just ended up replacing x with a random string like "zcx__x" and then replacing y and then replacing x back to y.
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Sep 8 2017 07:23pm
Quote (EvilBuddha @ Sep 8 2017 09:18pm)
Thought so. I just ended up replacing x with a random string like "zcx__x" and then replacing y and then replacing x back to y.


if this is for an assignment or someone is evaluating how you write your code, don't.

if this is just for your own purposes, that's fine.
Member
Posts: 1,039
Joined: Jul 8 2008
Gold: 1,939.50
Sep 10 2017 07:08pm
Replacing twice could produce errors so. You could iterate through each character and replace as you go. Java 8 way to do this using streams is something like:

Code

str.chars()
.parallel()
.mapToObj(c -> c == 'x' ? "y" : (c == 'y' ? "x" : Character.toString((char)c)))
.collect(Collectors.joining());
Member
Posts: 2,754
Joined: Nov 26 2007
Gold: 1,339.81
Sep 12 2017 09:03am
maybe do something like this

Code


String string = "0000000yyy00000xxx0000000y00000x";
System.out.println( "Before: " + string );
StringBuilder sb = new StringBuilder( );
for ( int i = 0; i < string.length( ); i++ ) {
char temp = string.charAt( i );
if ( temp == 'y' ) {
temp = 'x';
} else if ( temp == 'x' ) {
temp = 'y';
}
sb.append( temp );
}
string = sb.toString( );

System.out.println( "After: " + string );



Output

Before: 0000000yyy00000xxx0000000y00000x
After: 0000000xxx00000yyy0000000x00000y

This post was edited by labatymo on Sep 12 2017 09:04am
Member
Posts: 16,621
Joined: Jan 7 2017
Gold: 90.58
Sep 21 2017 12:37pm
Use Godot, then android export

much better ui tools
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll