I have a code here that changes the color of a word from a sentence. Violet if the word found is of the same position. Yellow if the answer contains a word but of a different position and red if the word is not found.
My problem right now is that the color changes to violet even though the word is of different position. I also tried to use splitInput[i].contains(splitAnswer[i]) to change the word to yellow but i got a repeated words for example "It was a a sample sample sentence sentence".
String answer = "This is a sample sentence"
String userInput = "It was a sample sentence"
boolean wordFound = false;
String[] splitAnswer = answer.split(" ");
String[] splitInput = userInput.split(" ");
for (int i=0; i<splitAnswer.length;i++)
{
for (int j=0;j<splitInput.length;j++)
{
if(splitInput[i].equalsIgnoreCase(splitAnswer[i]))
{
wordFound = true;
//color the word to violet
}
{
if(wordFound==false)
{
//color the word to red
}
//display the sentence
wordFound == false;
}
String answer = "This is a sample sentence";
String userInput = "It was a sample sentence";
boolean wordFound = false;
String[] splitAnswer = answer.split(" ");
String[] splitInput = userInput.split(" ");
for (int i=0; i<splitAnswer.length;i++)
{
if (splitInput[i].equalsIgnoreCase(splitAnswer[i]))
{
System.out.println ("Word found");
}
else if(!wordFound)
{
System.out.println ("Word Not found");
}
}
Related
I have a TextView which could potentially contain a clickable link. I want to add a click listener to the TextView but still when a link is clicked, I want it to be handled normally by Linkify.
It took me a while to figure this out and I wanted to share the answer since it's been working well so, enjoy!
This code traverses the string by separating characters at the space character: " ".
It then checks each 'word' for a link.
TextView textView = new TextView(context) {
#Override
public boolean onTouchEvent(MotionEvent event) {
final String text = getText().toString();
final SpannableString spannableString = new SpannableString(text);
Linkify.addLinks(spannableString, Linkify.ALL);
final URLSpan[] spans = spannableString.getSpans(0, text.length(), URLSpan.class);
final int indexOfCharClicked = getOffsetForPosition(event.getX(), event.getY()) + 1; //Change 0-index to 1-index
final String [] words = text.split(" ");
int numCharsTraversed = 0;
//Find the word that was clicked and check if it's a link
for (String word : words) {
if (numCharsTraversed + word.length() < indexOfCharClicked) {
numCharsTraversed += word.length() + 1; // + 1 for the space
} else {
for (URLSpan span : spans) {
if (span.getURL().contains(word) || word.contains(span.getURL())) {
//If the clicked word is a link, calling super will invoke the appropriate action
return super.onTouchEvent(event);
}
}
break;
}
}
//If we're here, it means regular text was clicked, not a link
doSomeAction();
return true;
}
};
I had a problem when I type the text I do not want the keyboard changes automatically, but after a space keyboard changes to the original state.
For example, I want to dial numbers that I move into this state the keyboard: But when I need to enter the number followed by a space, the keyboard itself is changed automatically:And it is necessary that the user himself can change the state of the keyboard, if it is necessary to enter characters. I use a mask on the text of Edit Text. With the help of this library set mask: MaskFormatter. an example of a mask: private static final String MASK = "99 AA 999999";
private EditText mInputCertificate;
#Override
public void setViews(View rootView, Bundle savedInstanceState) {
// Some code
mInputCertificate = (EditText) rootView.findViewById(R.id.input_car_certificate);
MaskFormatter maskFormatter = new MaskFormatter(MASK, mInputCertificate);
mInputCertificate.addTextChangedListener(maskFormatter);
}
There are ways to solve this problem?
I made my custom TextWatcher for EditText:
private String getString (String s) {
String newValue = s.replaceAll("\\s", "");
/*if (newValue.length() < 2 || newValue.length() >= 4) {
mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
} else {
mEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}*/
StringBuilder builder = new StringBuilder();
for (int i =0; i < newValue.length(); i++) {
if (i == 2 || i == 4) {
builder.append(' ');
builder.append(newValue.charAt(i));
} else {
builder.append(newValue.charAt(i));
}
}
return builder.toString();
}
#Override
public void afterTextChanged(Editable s) {
Log.d("EDITTEXT", "getEditable " + s);
String text = getString(s.toString());
mEditText.removeTextChangedListener(this);
mEditText.getText().clear();
mEditText.append(text.toUpperCase());
mEditText.addTextChangedListener(this);
mEditText.setSelection(mEditText.length());
}
This work for me. And I used .append(SomeText) instead .setText(SomeText).
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 am creating and android app that randomly generates any category, I would like to get the given random category word. This is the example string
String="The category Animals that starts with a letter J";
or
String="The category Colors that starts with a letter V";
I need to get the word Animals or Colors every random String is generated
A not so advanced solution, but easy to understand:
public void findCategory() {
String string = "The category Colors that starts with a letter V";
String[] split = string.split(" ");
int i;
for (i = 0; i < split.length; i++) {
if ("category".equals(split[i])) {
break;
}
}
System.out.println(split[i + 1]);
}
You may use regex.
Matcher m = Pattern.compile("\\bcategory\\s+(\\S+)").matcher(str);
while(m.find()) {
System.out.println(m.group(1));
}
OR
Matcher m = Pattern.compile("(?<=\\bcategory\\s)\\S+").matcher(str);
while(m.find()) {
System.out.println(m.group());
}
Please use Matcher and Pattern -
String input = "The category Animals that starts with a letter J";
Matcher m1 = Pattern.compile("^The category (.*) that starts with a letter (.*)$").matcher(input);
if(m1.find()) {
String _thirdWord = m1.group(1); // Animals
String _lastWord = m1.group(2); // J
System.out.println("Third word : "+_thirdWord);
System.out.println("Last Word : "+_lastWord);
}
Use this, it might fix your issue
String string = "The category Colors that starts with a letter V";
String[] ar = string.split(" ");
System.out.println(ar[2]);
I have already used following options to make each starting letter of a word Uppercase
<EditText
android:inputType="text|textCapWords"/>
While typing the user has option on the keyboard to change the case of letter i.e. the user with this option can easily type lowercase letters.
Further,I want text on my EditText to be on this format
Each Starting Letter Of A Word Must Be In Uppercase And All Other Letter Of The Word Be In Lowercase.
Meaning,when the user inputs
each StArting LeTTer of a word musT be in uppercase and all other leTTer of the word be in lowercase
, it will be automatically converted to above format.
I have tried using TextWatcher and string.split(\\s+) to get all the words and then make each and every word to follow the above format. But I always end up getting error.
So if there is any solution,it would be great.I want this to work in the manner InputFilter.AllCaps.
This is my code so far
private void changeToUpperCase(String inputString) {
if (inputString != null && inputString.trim().length() > 0) {
// businessName.addTextChangedListener(null);
String[] splitString = inputString.split("\\s+");
int length = splitString.length;
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < length; i++) {
String convertedString = splitString[i];
stringBuffer.append(Character.toUpperCase(convertedString
.charAt(0)));
stringBuffer.append(convertedString.substring(1).toLowerCase());
stringBuffer.append(" ");
}
Log.i("changed String", stringBuffer.toString());
// businessName.setText(stringBuffer.toString());
stringBuffer.delete(0, stringBuffer.length());
stringBuffer = null;
// businessName.addTextChangedListener(this);
}
}
This function I am calling from TextWatcher, afterTextChanged(Editable s)
In the layout xml, add android:capitalize="sentences"
The options for android:capitalize are following :
android:capitalize="none" : which won't automatically capitalize anything.
android:capitalize="sentences" : which will capitalize the first word of each sentence.
android:capitalize="words" : which will capitalize the first letter of every word.
android:capitalize="characters" : which will capitalize every character.
Update:
As android:capitalize is deprecated now need to use:
android:inputType="textCapWords"
change your input type programmatically.
If you are in View layout than use this code
EditText text = new EditText(context);
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); // which will capitalize the first letter of every word.
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS); //which will capitalize every character.
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); //which will capitalize the first word of each sentence.
addView(text);
and if you are in Activity
EditText text = new EditText(this);
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); // which will capitalize the first letter of every word.
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS); //which will capitalize every character.
text.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); //which will capitalize the first word of each sentence.
setContentView(text);
To make first letter capital of every word:
android:inputType="textCapWords"
To make first letter capital of every sentence:
android:inputType="textCapSentences"
To make every letter capital:
android:inputType="textCapCharacters"
Try this,
txtView.setText(WordUtils.capitalize("text view")
WordUtils.java
public class WordUtils {
public static String capitalize(String str) {
return capitalize(str, (char[]) null);
}
public static String capitalize(String str, char... delimiters) {
int delimLen = delimiters == null ? -1 : delimiters.length;
if (!TextUtils.isEmpty(str) && delimLen != 0) {
char[] buffer = str.toCharArray();
boolean capitalizeNext = true;
for (int i = 0; i < buffer.length; ++i) {
char ch = buffer[i];
if (isDelimiter(ch, delimiters)) {
capitalizeNext = true;
} else if (capitalizeNext) {
buffer[i] = Character.toTitleCase(ch);
capitalizeNext = false;
}
}
return new String(buffer);
} else {
return str;
}
}
private static boolean isDelimiter(char ch, char[] delimiters) {
if (delimiters == null) {
return Character.isWhitespace(ch);
} else {
char[] arr$ = delimiters;
int len$ = delimiters.length;
for (int i$ = 0; i$ < len$; ++i$) {
char delimiter = arr$[i$];
if (ch == delimiter) {
return true;
}
}
return false;
}
}
}
android:capitalize is deprecated. Use inputType instead.