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");
Related
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"
I was wondering how I could programmatically edit strings in android. I am displaying strings from my device to my website, and the apostrophes ruin the PHP output. so in order to fix this, I needed to add character breaks, ie: the backslash '\'.
For example, if I have this string: I love filiberto's!
I need android to edit it to: I love filiberto\'s!
However, each string is going to be different, and there will also be other characters that I have to escape from . How can I do this?
I was wondering how I could programmatically edit strings in android. I am displaying strings from my device to my website, and the apostrophes ruin the PHP output. so in order to fix this, I needed to add character breaks, ie: the backslash '\'.
This is what I have so far, thanks to ANJ for base code...:
if(title.contains("'")) {
int i;
int len = title.length();
char[] temp = new char[len + 1]; //plus one because gotta add new
int k = title.indexOf("'"); //location of apostrophe
for (i = 0; i < k; i++) { //all the letters before the apostrophe
temp[i] = title.charAt(i); //assign letters to array based on index
}
temp[k] = 'L'; // the L is for testing purposes
for (i = k+1; i == len; i++) { //all the letters after apostrophe, to end
temp[i] = title.charAt(i); //finish the original string, same array
}
title = temp.toString(); //output array to string (?)
Log.d("this is", title); //outputs gibberish
}
Which outputs random characters.. not even similar to my starting string. Does anyone know what could be causing this? For example, the string "Lol'ok" turns into >> "%5BC%4042ed0380"
I am assuming you are storing the string somewhere. Lets say the string is: str.
You can use a temporary array to add the '/'. For a single string:
int len = str.length();
char [] temp = new char[len+1]; //Temporary Array
int k = str.indexOf("'"), i; //Finding index of "'"
for(i=0; i<k-1; i++)
{
temp[i] = str.charAt(i); //Copying the string before '
}
temp[k] = '/'; //Placing "/" before '
for(i=k; j<len; j++)
{
temp[i+1] = str.charAt(i); //Copying rest of the string
}
String newstr = temp.toString(); //Converting array to string
You can use the same for multiple strings. Just make it as a function and call it whenever you want.
The String API has a number of API calls that could help, for example String.replaceAll. But...
apostrophes ruin the PHP output
Then fix the PHP code rather than require "clean" input. Best option would be to select a well supported transport format (say JSON or XML) and let the Json API on each end handle escape code.
I try to get only this part "9916-4203" in "Region Code:9916-4203 " in android. How can I do this?
I tried below code, I used substring method but it doesn't work:
firstNumber = Integer.parseInt(message.substring(11, 19));
If you know that string contains "Region Code:" couldn't you do a replace?
message = message.replace("Region Code:", "");
Assumed that you have only one phone number in your String, the following will remove any non-digit characters and parse the resulting number:
public static int getNumber(String num){
String tmp = "";
for(int i=0;i<num.length();i++){
if(Character.isDigit(num.charAt(i)))
tmp += num.charAt(i);
}
return Integer.parseInt(tmp);
}
Output in your case: 99164203
And as already mentioned, you won't be able to parse any String to Integer in case there are any non-digit characters
Im going to guess that what you want to extract is the full region code text minus the title. So maybe using regex would be a good simple fit for you?
String myString = "Region Code:9916-4203";
String match = "";
String pattern = "\:(.*)";
Pattern regEx = Pattern.compile(pattern);
Matcher m = regEx.matcher(myString);
// Find instance of pattern matches
Matcher m = regEx.matcher(myString);
if (m.find()) {
match = m.group(0);
}
Variable match will contain "9916-4203"
This should work for you.
Java code sourced from http://android-elements.blogspot.in/2011/04/regular-expressions-in-android.html
In Java the substring() method works with the first parameter being inclusive and the second parameter being exclusive. Meaning "Hello".substring(0, 2); will result in the string He.
In addition to excluding the parsing of something that isn't a number like #Opiatefuchs mentioned, your substring method should instead be message.substring(12, 21).
I have the following String ressource:
<string name="foo">This is a {0} test. Hello {1}</string>
Now I want to pass the values 1 and foo when calling:
getResources().getText(R.string.foo)
how to make this? Or is it not possible?
getResources().getString(R.string.foo, 1, "foo"); but string should be using string format ... so your string in string should looks like:
<string name="foo">This is a %d test. Hello %s</string>
I'm not too sure if Java has something like this inbuilt. I did once write a method that would do the exact thing you're looking for, however:
public static String format(String str, Object... objects)
{
String tag = "";
for (int i = 0; i < objects.length; i++)
{
tag = "\\{" + i + "\\}";
str = str.replaceFirst(tag, objects[i].toString());
}
return str;
}
And this would format the string, to replace the '{i}' with the objects passed; just like in C#.
example:
format(getResources().getString(R.string.foo), "cool", "world!");
You can do it this way :
string name="foo">This is a %d test. Hello %s string>
with
getString(R.string.foo, 1, "foo");
Source : Are parameters in strings.xml possible?
You can find more information on formatting and formats here : http://developer.android.com/reference/java/util/Formatter.html
I believe that the simplest way to do what you're wanting is to save the line of code you have to a variable then use the Java String replace() function.
String fooText = getResources().getText(R.string.foo);
fooText = fooText.replace("{0}", myZeroVar);
fooText = fooText.replace("{1}", myOneVar);
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.