This question already has answers here:
Capitalize first word of a sentence in a string with multiple sentences
(6 answers)
Closed 5 years ago.
My app receives a large amount of paragraph length text. Some of it is all in upper case, some all lower and some a mix. I would like to convert it to sentence case i.e. all sentences should start with an uppercase letter. What would be the most efficient way to perform the conversion? - I could not find any sample code or a library to do this.
The code referenced in the links above did not quite work, so I extended it as follows to turn text like:
"this SENTENce is not neat. neither IS this sentence."
into
"This sentence is not neat. Neither is this sentence."
public static String sentenceCaseForText(String text) {
if (text == null) return "";
int pos = 0;
boolean capitalize = true;
StringBuilder sb = new StringBuilder(text);
while (pos < sb.length()) {
if (capitalize && !Character.isWhitespace(sb.charAt(pos))) {
sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos)));
}
else if (!capitalize && !Character.isWhitespace(sb.charAt(pos))) {
sb.setCharAt(pos, Character.toLowerCase(sb.charAt(pos)));
}
if (sb.charAt(pos) == '.' || (capitalize && Character.isWhitespace(sb.charAt(pos)))) {
capitalize = true;
}
else {
capitalize = false;
}
pos++;
}
return sb.toString();
}
Related
I have a string (length 3-8) assigned to a variable (text). I want to check whether the 2nd and 3rd characters are NOT numeric (a letter or symbol or space..or anything other than numbers).
Elementary way to do this could be:
if(((text.charAt(1)-'0')>=0)&&(text.charAt(1)-'0')<10))||((text.charAt(2)-'0')>=0)&&(text.charAt(2)-'0')<10)))
{
//do nothing, since this means 2nd and/or 3rd characters in the string are numeric
}
else
{
// Your condition is met
}
You could also use REGEX's , if your checking is still more complicated.
Here is Another way to achieve this:
boolean isNumeric = true;
String test = "testing";
char second = test.charAt(1);
char third = test.charAt(2);
try {
Integer.parseInt(String.valueOf(second));
Integer.parseInt(String.valueOf(third));
} catch(NumberFormatException e) {
isNumeric = false;
}
System.out.println("Contains Number in 2nd and 3rd or both position: " + isNumeric);
You might make use of the String.IndexOf(String) method, like:
String digits = "0123456789";
String s2 = text.substring(2,3);
String s3 = text.substring(3,4);
boolean valid = (digits.indexOf(s2) > -1) && (digits.indexOf(s3) > -1);
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.
I'm a complete programming noob so go easy...
So I'm wondering how I would go about checking the edittext string to see if it "isBlank" using this isblank Boolean.
I know its probably a very easy answer but I just can't seem to get my head around it.
Any help appreciated.
public static boolean isBlank(String string) {
if (string == null || string.length() == 0)
return true;
int l = string.length();
for (int i = 0; i < l; i++) {
if (!Character.isWhitespace(string.codePointAt(i)))
return false;
}
return true;
}
**Thanks Heaps guys all helped alot!!.. If I could +1 I would.
You can write your method much shorter, like so:
static boolean isBlank(String string) {
return string == null || string.trim().length() == 0;
}
The trim() method removes all whitespace characters from beginning and end of a string. If what remains has length == 0, the whole string must have consisted of whitespace only.
The usage in your code depends on your need, but generally you'll use it in if() statements to make the code more readable:
String foo = "... some string ...";
if (isBlank(foo)) {
// foo is empty or only contains whitespace
} else {
// foo contains some text.
}
You can do this in single line.
if(edittext.getText().toString().trim().length()>0){
Syste.out.println("Not Blank");
}else{
Syste.out.println("Blank");
}
Like this:
if (isBlank(edittext.getText().toString())) {
// Blank
} else {
// Not blank
}
You can do it in this way:
Declare Class level variable:
boolean blank = false;
public static boolean isBlank(String string) {
if (string == null || string.trim().length() == 0){
blank = true;
}
else{
blank = false;
}
return blank;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beta);
ed_code = (EditText) findViewById(R.id.et_beta_01);
bu_ok = (Button) findViewById(R.id.bu_beta);
bu_ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String code = ed_code.getText().toString();
String target = "vsi8";
Log.v(TAG, code+"="+target);
if(code == target){
Intent intent = new Intent(BetaCheck.this, AppMenu.class);
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(), "wrong", Toast.LENGTH_SHORT).show();
ed_code.setText("");
}
}
});
}
It seems that the the if statement does not understand that the 2 values are equal.
Thanks for the help
Strings, should be compared using .equals and not ==. (== checks for reference equality and not for content equality.)
That is, change
if(code == target)
to
if(code.equals(target))
Related question:
How do I compare strings in Java?
If you want compare string values, you should use the equals() method, as in str.equals(value).
This is a common pitfal in java. Basically what aioobe said. Here's the code...
It can be tricky. If you do:
if( "a" == "a" )
You will get true because the compiler will just see two static strings that are equal just 'reuse' one. The == operator for String compares the REFERENCES, meaning it's testing to see if they are the same object. Even a case of:
String a = "a" ;
if (a == "a") {
You'll still get true because again the string gets recycled when the compiler optimizes that code to reuse the first "a" for the second to save space.
Now in the following case, we generate an empty string, manipulate it by appending "a"(not really, strings are immutable, so we end up generating a 3rd string BUT that is a different one since the JVM isn't going to waste its time looking for an existing string that's the same.
class tmp {
public static void main(String arg[]) {
String a = "" ;
a = a+"a" ;
if( a == "a" ) {
System.out.println("true") ;
}
else {
System.out.println("false") ;
}
if( "a".compareTo("a") == 0 ) {
System.out.println("true") ;
}
else {
System.out.println("false") ;
}
System.out.println("a = '" + a + "'") ;
}
}
Use code.equals(target) instead of code == target
http://bimal4u.wordpress.com/2007/03/29/what-is-the-difference-between-aequalsb-and-a-b/
Replace code == target with code.equals(target)
You should try the following code, because references of two strings, even if the strings are the same, are not the same.
if (something.equals(someOtherThing)) {
// …
}
comparing two strings wont work with == . It is only when u compare a value...
so plz try something like below
if (strcmp(code, target) == 0)
or
if (code.equals(target))
In my application there is a search option. If the user enters a search value, I have to get a value from the webservice. I am getting a large webservice value. In my webservice string values are coming. I am getting like <> like xml character entity reference like. I want to replace all characters and parse xml. Can anybody tell me how to do this and give an example?
I tried with StringBuffer for unescapexml character, I am getting out of memory error
public String unescapeXML(String str) {
if (str == null || str.length() == 0)
return "";
StringBuffer buf = new StringBuffer();
int len = str.length();
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
if (c == '&') {
int pos = str.indexOf(";", i);
if (pos == -1) { // Really evil
buf.append('&');
} else if (str.charAt(i + 1) == '#') {
int val = Integer.parseInt(str.substring(i + 2, pos), 16);
buf.append((char) val);
i = pos;
} else {
String substr = str.substring(i, pos + 1);
if (substr.equals("&"))
buf.append('&');
else if (substr.equals("<"))
buf.append('<');
else if (substr.equals(">"))
buf.append('>');
else if (substr.equals("""))
buf.append('"');
else if (substr.equals("'"))
buf.append('\'');
else if (substr.equals(" "))
buf.append(" ");
else
// ????
buf.append(substr);
i = pos;
}
} else {
buf.append(c);
}
}
return buf.toString();
}
I tried with stream, I am not able to do it. Can anybody give an example how to do this?
You should not parse it on your own. There are better ways - SAX or DOM.
This resource contains a lot of useful inforamtion about these both ways (and code examples too): http://onjava.com/pub/a/onjava/2002/06/26/xml.html
Take a look here in order to get more details about android included parsers :
http://developer.android.com/reference/javax/xml/parsers/package-summary.html
But make your own parser with SAX is probably the best choice in your case ;)