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]);
Related
In Custom TextView suppose if first character as a number then next character would be a character. How to find the first character amoung numbers.
If you are using Kotlin you may go for:
Capitalize first word:
var str = "whaever your string is..."
str.capitalize()
// Whaever your string is...
Capitalize each word
var str = "whaever your string is..."
val space = " "
val splitedStr = str.split(space)
str = splitedStr.joinToString (space){
it.capitalize()
}
// Whaever Your String Is...
Try this method by splitting the entire word
String input= "sentence";
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
textview.setText(output);
Output:
Sentence
You're looking for the inputType parameter in the xml layout file for the TextView. Basically in the layout file where you wish to set the TextView in camel case, add the following line:
android:inputType = "textCapWords"
//This would capitalise the first letter in every word.
If you wish to only capitalise the first letter in the TextView, use the following instead.
android:inputType = "textCapSentences"
//This would capitalise the first letter in every sentence.
If you have a textView which has more than one sentence, and you only want to capitalise the first letter in the TextView, I would recommend using code to do this:
String[] words = input.getText().toString().split(" ");
StringBuilder sb = new StringBuilder();
if (words[0].length() > 0) {
sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
}
}
String titleCaseValue = sb.toString();
Hope this helps :)
Use this function pass your string and return capitalize string.
public static String wordCapitalize(String words)
{
String str = "";
boolean isCap = false;
for(int i = 0; i < words.length(); i++){
if(isCap){
str += words.toUpperCase().charAt(i);
}else{
if(i==0){
str += words.toUpperCase().charAt(i);
}else {
str += words.toLowerCase().charAt(i);
}
}
if(words.charAt(i)==' '){
Utility.debug(1,TAG,"Value of i : "+i+" : "+words.charAt(i)+" : true");
isCap = true;
}else{
Utility.debug(1,TAG,"Value of i : "+i+" : "+words.charAt(i)+" : false");
isCap = false;
}
}
Utility.debug(1,TAG,"Result : "+str);
return str;
}
String text = textView.getText().toString();
for(Character c : text){
if(c.isLetter){
//First letter found
break;
}
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"
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);
I got stuck in this regular expression as I am having a string as:
String str = "/abcde/samplename.xyz"
I want to replace this samplename.xyz from a new string, so how can I apply the regular expression in this ?
Try this out.....
String str = "/abcde/samplename.xyz";
String req=str.substring(str.lastIndexOf("/") + 1);
now you get the value of: req=samplename.xyz and you can replace with which ever string value you want
String rep=str.replace(req, "");
String startString=str.substring(0, str.lastIndexOf('/') + 1)
String str = "/abcde/samplename.xyz";
String str1 = str.substring(0, str.lastIndexOf('/') + 1);
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();
Log.i("strArr[1]=", "" + str1);
check this.i hope its useful to you.
Try this::
String str = "/abcde/samplename.xyz";
String result=str.substring(0, str.lastIndexOf('/') + 1);
Log.d("Hello","Result="+result);
String[] result = str.split("/");
String LastItem = result[str.length -1];
LastItem.replace(newString);