Android - how to replace part of a string by another string? - java

I have strings with some numbers and english words and I need to translate them to my mother tongue by finding them and replacing them by locallized version of this word. Do you know how to easily achieve replacing words in a string?
Thanks
Edit:
I have tried (part of a string "to" should be replaced by "xyz"):
string.replace("to", "xyz")
But it is not working...

It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:
string = string.replace("to", "xyz");
or
String newString = string.replace("to", "xyz");
API Docs
public String replace (CharSequence target, CharSequence replacement)
Since: API Level 1
Copies this string replacing
occurrences of the specified target
sequence with another sequence. The
string is processed from the beginning
to the end.
Parameters
target the sequence to replace.
replacement the replacement
sequence.
Returns the resulting string.
Throws NullPointerException if target or replacement is null.

MAY BE INTERESTING TO YOU:
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.

In kotlin there is no replaceAll, so I created this loop to replace repeated values ​​in a string or any variable.
var someValue = "https://www.google.com.br/"
while (someValue.contains(".")) {
someValue = someValue.replace(".", "")
}
Log.d("newValue :", someValue)
// in that case the stitches have been removed
//https://wwwgooglecombr/

String str = "to";
str.replace("to", "xyz");
Just try it :)

rekaszeru
I noticed that you commented in 2011 but i thought i should post this answer anyway, in case anyone needs to "replace the original string" and runs into this answer ..
Im using a EditText as an example
// GIVE TARGET TEXT BOX A NAME
EditText textbox = (EditText) findViewById(R.id.your_textboxID);
// STRING TO REPLACE
String oldText = "hello"
String newText = "Hi";
String textBoxText = textbox.getText().toString();
// REPLACE STRINGS WITH RETURNED STRINGS
String returnedString = textBoxText.replace( oldText, newText );
// USE RETURNED STRINGS TO REPLACE NEW STRING INSIDE TEXTBOX
textbox.setText(returnedString);
This is untested, but it's just an example of using the returned string to replace the original layouts string with setText() !
Obviously this example requires that you have a EditText with the ID set to your_textboxID

You're doing only one mistake.
use replaceAll() function over there.
e.g.
String str = "Hi";
String str1 = "hello";
str.replaceAll( str, str1 );

Related

String Replace Based On Variable Value

I've the following string: {"array 1":[ ....
And I would like to remove everything preceding [.
For that I use: .replace("{\"array 1\":", ""); and that works well.
However, I've several arrays, so I'd like to do the replace based on a variable that holds the array name.
For example:
String arr_name = "array 1";
....replace('{\"arr_name\":", "");
Is it possible to use variable key to replace a string?
EDIT:
I've ended up adding another element to parse the array in JSON which removed its name.
Thank you all for the quick comments and suggestions.
you can do a string format, here is an example of that :
String arr_name = "array 1";
....replace(String.format ("{\"%s\"", arr_name), "");
Just use a substring, starting at the index of [.
String input = "{\"array 1\":[key:value...";
String result = input.substring(input.indexOf('['));
This gives [key.value...

Java String.replace/replaceAll not working

So, I'm trying to parse a String input in Java that contains (opening) square brackets. I have str.replace("\\[", ""), but this does absolutely nothing. I've tried replaceAll also, with more than one different regex, but the output is always unchanged. Part of me wonders if this is possibly caused by the fact that all my back-slash characters appear as yen symbols (ever since I added Japanese to my languages), but it's been that way for over a year and hasn't caused me any issues like this before.
Any idea what I might be doing wrong here?
Strings are immutable in Java. Make sure you re-assign the return value to the same String variable:
str = str.replaceAll("\\[", "");
For the normal replace method, you don't need to escape the bracket:
str = str.replace("[", "");
public String replaceAll(String regex, String replacement)
As shown in the code above, replaceAll method expects first argument as regular expression and hence you need to escape characters like "(", ")" etc (with "\") if these exists in your replacement text which is to be replaced out of the string. For example :
String oldString = "This is (stringTobeReplaced) with brackets.";
String newString = oldString.replaceAll("\\(stringTobeReplaced\\)", "");
System.out.println(newString); // will output "This is with brackets."
Another way of doing this is to use Pattern.quote("str") :
String newString = oldString.replaceAll(Pattern.quote("(stringTobeReplaced)"), "");
This will consider the string as literal to be replaced.
As always, the problem is not that "xxx doesn't work", it is that you don't know how to use it.
First things first:
a String is immutable; if you read the javadoc of .replace() and .replaceAll(), you will see that both specify that a new String instance is returned;
replace() accepts a string literal as its first argument, not a regex literal.
Which means that you probably meant to do:
str = str.replace("[", "");
If you only ever do:
str.replace("[", "");
then the new instance will be created but you ignore it...
In addition, and this is a common trap with String (the other being that .matches() is misnamed), in spite of their respective names, .replace() does replace all occurrences of its first argument with its second argument; the only difference is that .replaceAll() accepts a regex as a first argument, and a "regex aware" expression as its second argument; for more details, see the javadoc of Matcher's .replaceAll().
For it to work it has to be inside a method.
for example:
public class AnyClass {
String str = "gtrg4\r\n" + "grtgy\r\n" + "grtht\r\n" + "htrjt\r\n" + "jtyjr\r\n" + "kytht";
public String getStringModified() {
str.replaceAll("\r\n", "");
return str;
}
}

Replace String variable with exact string

If i want to replace one string variable with exact string in java, what can I do?
I know that replace in java , replace one exact string with another, but now i have string variable and i want to replace it's content with another exact string.
for example:
`String str="abcd";
String rep="cd";`
Now I want to replace rep content with"kj"
It means that I want to have str="abkj" at last.
If I understand your question, you could use String.replace(CharSequence, CharSequence) like
String str="abcd";
String rep="cd";
String nv = "kj";
str = str.replace(rep, nv); // <-- old, new
System.out.println(str);
Output is (the requested)
abkj
i think he wants:
String toReplace = "REPLACE_ME";
"REPLACE_ME What a nice day!".replace(toReplace,"");
"REPLACEME What a nice day!".replace(toReplace,"") results in:
" What a nice day!"

Splitting string into substring in Java

I have one string and I want to split it into substring in Java, originally the string is like this
Node( <http://www.mooney.net/geo#wisconsin> )
Now I want to split it into substring by (#), and this is my code for doing it
String[] split = row.split("#");
String word = split[1].trim().substring(0, (split[1].length() -1));
Now this code is working but it gives me
"wisconsin>"
the last work what I want is just the work "wisconsin" without ">" this sign, if someone have an idea please help me, thanks in advance.
Java1.7 DOC for String class
Actually it gives you output as "wisconsin> " (include space)
Make subString() as
String word = split[1].trim().substring(0, (split[1].length()-3));
Then you will get output as
wisconsin
Tutorials Point String subString() method reference
Consider
String split[] = row.split("#|<|>");
which delivers a String array like this,
{"http://www.mooney.net/geo", "wisconsin"}
Get the last element, at index split.length()-1.
String string = "Enter parts here";
String[] parts = string.split("-");
String part1 = parts[0];
String part2 = parts[1];
you can just split like you did before once more (with > instead of #) and use the element [0] istead of [1]
You can just use replace like.
word.replace(char oldChar, char newChar)
Hope that helps
You can use Java String Class's subString() method.
Refer to this link.

How to get specific string out of long string

I have the following String (it is variable, but classpath is always the same):
C:.Users.mho.Desktop.Eclipse.workspace.GIT.BLUBB...bin.de.test.class.mho.communication.InterfaceXmlHandler
and I want to get just
de.test.class.mho.communication.InterfaceXmlHandler
out of this string. The end
InterfaceXmlHandler
is variable, also the beginning before 'de' and the path itself is variable too, but
de.test.class.mho.
isn't variable.
Why not just use
String result = str.substring(str.lastIndexOf("de.test.class.mho."));
Instead of splitting you could get rid of the beginning of the string:
String input = "C:.Users.mho.Desktop.Eclipse.workspace.GIT.BLUBB...bin.de.test.class.mho.communication.InterfaceXmlHandler";
String output = input.replaceAll(".*(de\\.test\\.class\\.mho.*)", "$1");
You can create a string-array with String.split("de.test.class.mho."). The Array will contain two Strings, the second String will be what you want.
String longString = ""; //whatever
String[] urlArr = longString.split("de.test.class.mho.");
String result;
if(urlArr.length > 1) {
result = "de.test.class.mho." urlArr[1]; //de.test.class.mho.whatever.whatever.whatever
}
You can use replaceAll() to "extract" the part you want:
String part = str.replaceAll(".*(?=de\\.test\\.class\\.mho\\.)", "");
This uses a look-ahead to find all characters before the target, and replace them with a blank (ie delete them).
You could quite reasonably ignore escaping the dots for brevity:
String part = str.replaceAll(".*(?=de.test.class.mho.)", "");
I doubt it would give a different result.

Categories