I have a String which I am getting from API (no control over it). When the String contains a special character like an apostrophe, it will be converted to something else.
It looks something like this:
text_view.text = "Hannah's Law"
When displayed on Android, it will be:
Hannah's Law
I tried to convert the String to byteArray and then encode to UTF-8 but no luck:
val byteArray = template.execute(bindingDictionary).toByteArray() // This is the Actual String
String(byteArray,Charsets.UTF_8) // Did not work
'
is HTML for the apostrophe. You can use fromHtml to convert that to text with the apostrophe.
val fromApi = "Hannah's Law"
val textFromHtmlFromApi = HtmlCompat.fromHtml(fromApi, HtmlCompat.FROM_HTML_MODE_LEGACY)
text_view.text = textFromHtmlFromApi
use unicode symbols like here https://www.rapidtables.com/code/text/unicode-characters.html
for example instead
String str = "Hannah's Law"
use
String str = "Hannah\u0027s Law"
same thing if you need for example space in the end of string
String str = "string with space in the end\u0020"
for Kotlin use
var str: String = "string with space in the end\u0020"
Related
I am trying to concatenate 2 String but not sure how to go about it.
this is my code:
val word = R.string.word
and i'm trying to append it with "$currentPage/5" inside the setText("$currentPage/5")
i tried to make it in this way setText("$word $currentPage/5")
and this way setText("${R.string.value} $currentPage/5")
and it did not work , it only shows me numbers not the text
try to use this:
val word = getString(R.string.word)
text_view.text = "$word $currentPage/5"
If you want to edit your value (e.g. current page) wrap it with {}
E.g.
val word = getString(R.string.word)
text_view.text = "$word ${currentPage/5}"
Remember to use proper kotlin syntax
In Kotlin, the concatenation of string can be done by **interpolation/templates**.
val a = "Its"
val b = "Kotlin!"
val c = "$a $b"
The output will be Its Kotlin!
Or we can alson do concatenate using the **+ / plus() operator**:
val a = "String"
val b = "Concatenate"
val c = a + b
val d =a.plus(b)
print(c)
The output will be: StringConcatenate
print(d)
The output will be: StringConcatenate
Or you can concatenate using the StringBuilder which is a normal way to do that.
To concatenate two string, we could do
val concatenatedWord = "${resources.getString(R.string.value)}:
${number/3}."
If R.string.value was "The result" and number was 15, value of concatenatedWord will be "The result: 5."
Or we could also concatenate using the + operator or using StringBuilder.
But if you do
textView.text = "${resources.getString(R.string.value)}: ${number/3}."
AS will warn "Do not concatenate text displayed with setText." so, in the case of setting concatenated text in textview, consider using
String.format("%s: %d.", resources.getString(R.string.value):
number/3)
As a future resource and answer why the accepted answer works:-
String Templates:-
Strings may contain template expressions, i.e. pieces of code that are evaluated and whose results are concatenated into the string.
How to implement these?
A template expression should start with a dollar sign ($) and consists of either a simple name:
when the expression is a simple variable.
val i = 10
println("i = $i") // prints "i = 10"
or else arbitrary expression in curly braces:
val s = "abc"
println("$s.length is ${s.length}") // prints "abc.length is 3"
Note :- Templates are supported both inside raw strings and inside escaped strings.
val nameOfAnimal = "fish"
val speciesClass = "is an Aquatic Vertebrate"
println(nameOfAnimal.plus(speciesClass))
println(nameOfAnimal+speciesClass)
println("$nameOfAnimal $speciesClass")
Results:
fishis an Aquatic Vertebrate
fishis an Aquatic Vertebrate
fish is an Aquatic Vertebrate
Is it possible to change 1 char into String from code in Kotlin ?
I think yes, but I don't know how.
<string name="carID">Id: </string>
Currently I change whole String like:
carID.text = car.id.toString()
but I want add only number to this ID:
You can convert a char to a string:
val myChar = '1'
val myString = Character.toString(myChar )
Now, you can concat the new string to your other string:
val myIdString = "Id: $myString"
This is of course just the mechanics, you will need to adapt the code as you need and of course there are short-cuts if you want: this was purely for demonstration.
Change your string resource like this:
<string name="carID">Id: %1$s</string>
and you use it:
carID.text = String.format(getString(R.string.carID), "1")
the text will be: Id: 1
I want to read data from a raw file and replace the format in the text.
For example... In a raw file like this:
hello {0}, my name id {1}, my age is {2}....
When I use String.format, as shown below, the text loses its indentation.
String data = readTextFile(this, R.raw.input);
data = String.format(data, "world", "josh", "3");
Does anyone know how to do this without losing indentation?
Code that you provided looks more like String.format e.g from C#. String.format in Java does not work this way, it's more like printf.
You can manipulate your input to looks like this.
String input = "hello %s, my name id %s, my age is %s";
String.format(input, "world", "josh", "3");
output:
hello world, my name id josh, my age is 3
indentation should be the same
EDIT
If you want to use brackets you can use MessageFormat.format instead of String.format.
String messageInput = "hello {0}, my name id {1}, my age is {2}";
MessageFormat.format(messageInput,"world", "josh", "3");
You can use Regular Explessions with pattern like that: "{/d++}":
String format (String input, String... args) {
Pattern p = Pattern.compile("{/d++}");
String[] parts = p.split(input);
StringBuilder builder = new StringBuilder("");
int limit = Math.min(args.length, parts.length);
for(int i = 0; i < limit; i++){
builder.append(parts[i]).append(args[i]);
}
return builder.toString();
}
I found the solution for my problem.
there is a needed in one more variable, it's impossible to assignment into same variable
String data = readTextFile(this, R.raw.input);
String output = String.format(data, "world", "josh", "3");
In my Android Application when I am reading the particular data from NFC chip it's giving garbage values as show follows which is printed on Log
����������������
I used following line to remove garbage value
str.replaceAll("[^\\p{ASCII}]", "")
but it is not working.
Please provide me solution.
That is because � is not an ASCII character. It is a unicode character with (int) � returning 65533.
And your code str.replaceAll("[^\\p{ASCII}]", "") works perfectly fine.
scala> val str ="����������������"
str: String = ����������������
scala> str.replaceAll("[^\\p{ASCII}]", "")
res8: String = ""
You need to show more code and explain what exactly you are trying to do.
Better to retrieve the data in the form of UTF-8 format then it helps. try it out.
or convert the string to UTF-8 format
i.e, String _data=new String(str.getBytes(),"UTF-8");
it returns the data in UTF-8 format
One solution using this method .replaceAll("[^\\x00-\\x7F]", "")
String str = "jorgesys���������������� was here!";
str = str.replaceAll("[^\\x00-\\x7F]", ""));
so the result of str is:
jorgesys was here!
In my android app, I am getting the String from an Edit Text and using it as a parameter to call a web service and fetch JSON data.
Now, the method I use for getting the String value from Edit Text is like this :
final EditText edittext = (EditText) findViewById(R.id.search);
String k = edittext.getText().toString();
Now normally it works fine, but if we the text in Edit Text contains space then my app crashes.
for eg. - if someone types "food" in the Edit Text Box, then it's OK
but if somebody types "Indian food" it crashes.
How to remove spaces and get just the String ?
Isn't that just Java?
String k = edittext.getText().toString().replace(" ", "");
try this...
final EditText edittext = (EditText) findViewById(R.id.search);
String k = edittext.getText().toString();
String newData = k.replaceAll(" ", "%20");
and use "newData"
String email=recEmail.getText().toString().trim();
String password=recPassword.getText().toString().trim();
In the future, I highly recommend checking the Java String methods in the API. It's a lifeline to getting the most out of your Java environment.
You can easily remove all white spaces using something like this. But you'll face another serious problem if you just do that. For example if you have input
String input1 = "aa bb cc"; // output aabbcc
String input2 = "a abbcc"; // output aabbcc
String input3 = "aabb cc"; // output aabbcc
One solution will be to fix your application to accept white spaces in input string or use some other literal to replace the white spaces. If you are using only alphanumeric values you do something like this
String input1 = "aa bb cc"; // aa_bb_cc
String input2 = "a abbcc"; //a_abbcc
String input3 = "aabb cc"; //aabb_cc
And after all if you are don' caring about the loose of information you can use any approach you want.