I have string in forloop, I want add that in to another string like the given format
for (int i = 0; i < profiles.length(); i++) {
JSONObject c = profiles.getJSONObject(i);
String admnno = c.getString(TAG_ADMNNO);
}
The result should be like this
"Rajesh", "Mahesh", "Vijayakumar"
or
final CharSequence[] items = {"Rajesh", "Mahesh", "Vijayakumar"};
The adminno should be in double quotes and following comma. Its in android doin Background()
Use \" for this
For example String str="\"Rajesh\""
Try this,
if (TextUtils.isEmpty(string))
return "";
final int lastPos = string.length() - 1;
if (lastPos < 0 || (string.charAt(0) == '"' && string.charAt(lastPos) == '"'))
return string;
return "\"" + string + "\"";
Another option is to use Kotlin's multiline strings. Especially useful when you need hardcode big JSON for UTests:
val jsonString = """
{
"string_key": "value",
"boolean_key": true
}
"""
You can also try this
var id = "\"id\": \""
Output = "id": "
You have to escape the quote using \" like below:
public static String getQuotedString(String sample){
return "\"".concat(sample).concat("\"");
}
In Kotlin, you can use a variable value like this way
val searchText = "Android"
textview.text = "5 articles found for \"$searchText\""
For fixed string:
String str="5 articles found for \"IOS\" "
value is equal for
5 articles found for "IOS"
Related
its may be silly but am confused on that this i want to start count up to one and if press comma(,)then i want to count comma only, here how i am try.
String conCount;
conCount = "1";
int countComma = conCount.length() - conCount.replace(",", "").length();
String lenVar;
lenVar = conCount;
convert = String.valueOf(countComma);
if (conCount.length() == 0) {
lenVar = "0";
} else {
textViewConCount.setText(convert);
}
String editTextString = "abc,efg,pqr,xyz";
if (editTextString.contains(",")) {
int countStringsSeperatedByComma = 0;
countStringsSeperatedByComma = editTextString.split(",").length;
System.out.println("Count of strings seperated by comma : " + countStringsSeperatedByComma);
int commaCount = countStringsSeperatedByComma - 1;
System.out.println("Count of commas : " + commaCount);
} else {
System.out.println("Count of characters in editText string : " + editTextString.length());
}
Output for above condition will be :
Count of strings seperated by comma : 4
Count of commas : 3
Suppose if your string is "abcefgpqrxyz" i.e. without comma then it will execute else part and print characters count as 12 in this case
Count of characters in editText string : 12
Your question statement is so ambiguous. Elaborate it completely and explain your end result with example. It's regarding string functions, I can give you the answer about it if I understand it :) :D
thanks for that i got that answer like that.
String varStr = editextContact.getText().toString();
//int VarCount = editextContact.getText().length();
int countStringsSeperatedByComma = varStr.split(",").length;
String convet=String.valueOf(countStringsSeperatedByComma);
textViewConCount.setText(varStr);
if (varStr.length() == 0){
textViewConCount.setText("0");
}else {
textViewConCount.setText(convet);
}
i need to change the text="font roboto regular" to Font Roboto Regular in xml itself, how to do?
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="18sp"
android:textColor="#android:color/black"
android:fontFamily="roboto-regular"
android:text="font roboto regular"
android:inputType="textCapWords"
android:capitalize="words"/>
If someone looking for kotlin way of doing this, then code becomes very simple and beautiful.
yourTextView.text = yourText.split(' ').joinToString(" ") { it.capitalize() }
You can use this code.
String str = "font roboto regular";
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
for (String s : strArray) {
String cap = s.substring(0, 1).toUpperCase() + s.substring(1);
builder.append(cap + " ");
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(builder.toString());
Try this...
Method that convert first letter of each word in a string into an uppercase letter.
private String capitalize(String capString){
StringBuffer capBuffer = new StringBuffer();
Matcher capMatcher = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(capString);
while (capMatcher.find()){
capMatcher.appendReplacement(capBuffer, capMatcher.group(1).toUpperCase() + capMatcher.group(2).toLowerCase());
}
return capMatcher.appendTail(capBuffer).toString();
}
Usage:
String chars = capitalize("hello dream world");
//textView.setText(chars);
System.out.println("Output: "+chars);
Result:
Output: Hello Dream World
KOTLIN
val strArrayOBJ = "Your String".split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val builder = StringBuilder()
for (s in strArrayOBJ) {
val cap = s.substring(0, 1).toUpperCase() + s.substring(1)
builder.append("$cap ")
}
txt_OBJ.text=builder.toString()
Modification on the accepted answer to clean out any existing capital letters and prevent the trailing space that the accepted answer leaves behind.
public static String capitalize(#NonNull String input) {
String[] words = input.toLowerCase().split(" ");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (i > 0 && word.length() > 0) {
builder.append(" ");
}
String cap = word.substring(0, 1).toUpperCase() + word.substring(1);
builder.append(cap);
}
return builder.toString();
}
you can use this method to do it programmatically
public String wordFirstCap(String str)
{
String[] words = str.trim().split(" ");
StringBuilder ret = new StringBuilder();
for(int i = 0; i < words.length; i++)
{
if(words[i].trim().length() > 0)
{
Log.e("words[i].trim",""+words[i].trim().charAt(0));
ret.append(Character.toUpperCase(words[i].trim().charAt(0)));
ret.append(words[i].trim().substring(1));
if(i < words.length - 1) {
ret.append(' ');
}
}
}
return ret.toString();
}
refer this if you want to do it in xml.
You can use
private String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
refer this How to capitalize the first character of each word in a string
android:capitalize is deprecated.
Follow these steps: https://stackoverflow.com/a/31699306/4409113
Tap icon of ‘Settings’ on the Home screen of your Android Lollipop
Device
At the ‘Settings’ screen, scroll down to the PERSONAL section and
tap the ‘Language & input’ section.
At the ‘Language & input’ section, select your keyboard(which is
marked as current keyboard).
Now tap the ‘Preferences’.
Tap to check the ‘Auto – Capitalization’ to enable it.
And then it should work.
If it didn't, i'd rather to do that in Java.
https://stackoverflow.com/a/1149869/2725203
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
Another approach is to use StringTokenizer class. The below method works for any number of words in a sentence or in the EditText view. I used this to capitalize the full names field in an app.
public String capWordFirstLetter(String fullname)
{
String fname = "";
String s2;
StringTokenizer tokenizer = new StringTokenizer(fullname);
while (tokenizer.hasMoreTokens())
{
s2 = tokenizer.nextToken().toLowerCase();
if (fname.length() == 0)
fname += s2.substring(0, 1).toUpperCase() + s2.substring(1);
else
fname += " "+s2.substring(0, 1).toUpperCase() + s2.substring(1);
}
return fname;
}
in kotlin, string extension
fun String?.capitalizeText() = (this?.toLowerCase(Locale.getDefault())?.split(" ")?.joinToString(" ") { if (it.length <= 1) it else it.capitalize(Locale.getDefault()) }?.trimEnd())?.trim()
Kotlin extension function for capitalising each word
val String?.capitalizeEachWord
get() = (this?.lowercase(Locale.getDefault())?.split(" ")?.joinToString(" ") {
if (it.length <= 1) it else it.replaceFirstChar { firstChar ->
if (firstChar.isLowerCase()) firstChar.titlecase(
Locale.getDefault()
) else firstChar.toString()
}
}?.trimEnd())?.trim()
As the best way for achieving this used to be the capitalize() fun, but now it got depricated in kotlin. So we have an alternate for this. I've the use case where I'm getting a key from api that'll be customized at front end & will be shown apparently. The value is coming as "RECOMMENDED_OFFERS" which should be updated to be shown as "Recommended Offers".
I've created an extension function :
fun String.updateCapitalizedTextByRemovingUnderscore(specialChar: String): String
that takes a string which need to be replaced with white space (" ") & then customise the words as their 1st character would be in caps. So, the function body looks like :
fun String.updateCapitalizedTextByRemovingUnderscore(
specialChar: String = "") : String {
var tabName = this
// removing the special character coming in parameter & if
exist
if (spclChar.isNotEmpty() && this.contains(specialChar)) {
tabName = this.replace(spclChar, " ")
}
return tabName.lowercase().split(' ').joinToString(" ") {
it.replaceFirstChar { if (it.isLowerCase())
it.titlecase(Locale.getDefault()) else it.toString() } }
}
How to call the extension function :
textView.text =
"RECOMMENDED_OFFERS".updateCapitalizedTextByRemovingUnderscore("_")
OR
textView.text = <api_key>.updateCapitalizedTextByRemovingUnderscore("_")
The desired output will be :
Recommended Offers
Hope this will help.Happy coding :) Cheers!!
capitalize each word
public static String toTitleCase(String string) {
// Check if String is null
if (string == null) {
return null;
}
boolean whiteSpace = true;
StringBuilder builder = new StringBuilder(string); // String builder to store string
final int builderLength = builder.length();
// Loop through builder
for (int i = 0; i < builderLength; ++i) {
char c = builder.charAt(i); // Get character at builders position
if (whiteSpace) {
// Check if character is not white space
if (!Character.isWhitespace(c)) {
// Convert to title case and leave whitespace mode.
builder.setCharAt(i, Character.toTitleCase(c));
whiteSpace = false;
}
} else if (Character.isWhitespace(c)) {
whiteSpace = true; // Set character is white space
} else {
builder.setCharAt(i, Character.toLowerCase(c)); // Set character to lowercase
}
}
return builder.toString(); // Return builders text
}
use String to txt.setText(toTitleCase(stringVal))
don't use android:fontFamily to roboto-regular. hyphen not accept. please rename to roboto_regular.
To capitalize each word in a sentence use the below attribute in xml of that paticular textView.
android:inputType="textCapWords"
I want to get a text that it is a part of an string.For example: I have a string like "I am Vahid" and I want to get everything that it's after "am".
The result will be "Vahid"
How can I do it?
Try:
Example1
String[] separated = CurrentString.split("am");
separated[0]; // I am
separated[1]; // Vahid
Example2
StringTokenizer tokens = new StringTokenizer(CurrentString, "am");
String first = tokens.nextToken();// I am
String second = tokens.nextToken(); //Vahid
Try:
String text = "I am Vahid";
String after = "am";
int index = text.indexOf(after);
String result = "";
if(index != -1){
result = text.substring(index + after.length());
}
System.out.print(result);
Just use like this, call the method with your string.
public String trimString(String stringyouwanttoTrim)
{
if(stringyouwanttoTrim.contains("I am")
{
return stringyouwanttoTrim.split("I am")[1].trim();
}
else
{
return stringyouwanttoTrim;
}
}
If you prefer to split your sentence by blank space you could do like this :
String [] myStringElements = "I am Vahid".split(" ");
System.out.println("your name is " + myStringElements[myStringElements.length - 1]);
So if you are adding in a string, you can just add them via += method(the one i know and using atm). but how can you delete a word in a string/string array?
example: i have a string
String="Monday,Tuesday,Wednesday"
how do you make it into
String="Monday,Wednesday"
any help please?
You could use the replace method.
String sentence = "Monday,Tuesday,Wednesday";
String replaced = sentence.replace("Tuesday,", "");
its easy
just use
yourString = yourString.replaceAll("the text to replace", ""); //the second "" show empty string so the text will get replace by empty string
finally yourString will contain the text u desire Thats it :)
You can use the "public String replace(char oldChar, char newChar)" method if you want to remove "Tuesday" and not the second element
https://stackoverflow.com/questions/16702357/how-to-replace-a-substring-of-a-string
I think, i will use it for simplicity otherwise go to other suggested answer...
Use Arraylist for storing days:
ArrayList<String> days = new ArrayList<String>();
days.add("Monday");
days.add("Tuesday");
days.add("Wednesday");
Use it for creating days string:
public String getDays() {
String daysString = "";
for (int i = 0; i < days.size(); i++) {
if (i != 0)
daysString += ", ";
daysString += days.get(i);
}
return daysString;
}
And whenever you want to remove use
days.remove(1);
or
days.remove("Tuesday");
then again call getDays();
IInd Method if you want to use only string:
String list = "Monday,Tuesday,Wednesday";
System.out.println("New String : " + removeAtIndex(list, 1));
and
public String removeAtIndex(String string, int index) {
int currentPointer = 0;
int lastPointer = string.indexOf(",");
while (index != 0) {
currentPointer = string.indexOf(',', currentPointer) + 1;
lastPointer = string.indexOf(',', lastPointer + 1);
index--;
}
String subString = string.substring(currentPointer,
lastPointer == -1 ? string.length() : lastPointer);
return string.replace((currentPointer != 0 ? "," : "") + subString
+ (currentPointer == 0 ? "," : ""), "");
}
Something like this using a regular expression:
String contents = "Monday,Tuesday,Wednesday";
contents = contents.replaceAll("[\\,]+Tuesday|^Tuesday[\\,]*", "");
I have a String separated by commas as follows
1,2,4,6,8,11,14,15,16,17,18
This string is generated upon user input. Suppose the user wants to remove any of the numbers, I have to rebuild the string without the specified number.
If the current string is:
1,2,4,6,8,11,14,15,16,17,18
User intents to remove 1, the final string has to be:
2,4,6,8,11,14,15,16,17,18
I tried to achieve this using the following code:
//String num will be the number to be removed
old = tv.getText().toString(); //old string
newString = old.replace(num+",",""); //will be the new string
This might be working sometimes but it is sure that it won't work for the above example I have shown, if I try to remove the 1, it also removes the last part of 11, because there also exists 1.
well you can use this. Its the most simplest approach i can think of:
//String num will be the number to be removed
old=","+tv.getText().toString()+",";//old string commas added to remove trailing entries
newString=old.replace(","+num+",",",");// will be the new string
newString=newString.substring(1,newString.length()-1); // removing the extra commas added
This would work for what you want to do. I have added a comma at the start and end of your string so that you can also remove the first and last entries too.
You can split the string first and check for the number where you append those value that is not equivalent to the number that will get deleted;
sample:
String formated = "1,2,4,6,8,11,14,15,16,17,18";
String []s = formated.split(",");
StringBuilder newS = new StringBuilder();
for(String s2 : s)
{
if(!s2.equals("1"))
newS.append(s2 + ",");
}
if(newS.length() >= 1)
newS.deleteCharAt(newS.length() - 1);
System.out.println(newS);
result:
2,4,6,8,11,14,15,16,17,18
static public String removeItemFromCommaDelimitedString(String str, String item)
{
StringBuilder builder = new StringBuilder();
int count = 0;
String [] splits = str.split(",");
for (String s : splits)
{
if (item.equals(s) == false)
{
if (count != 0)
{
builder.append(',');
}
builder.append(s);
count++;
}
}
return builder.toString();
}
String old = "1,2,4,6,8,11,14,15,16,17,18";
int num = 11;
String toRemove = "," + num + "," ;
String oldString = "," + old + ",";
int index = oldString.indexOf(toRemove);
System.out.println(index);
String newString = null;
if(index > old.length() - toRemove.length() + 1){
newString = old.substring(0, index - 1);
}else{
newString = old.substring(0, index) + old.substring(index + toRemove.length() -1 , old.length());
}
System.out.println(newString);