In php, the method ucwords converts any string in a string where each words first character is in uppercase, and all other characters are lower case.
I always end up making my own implementation, and I'm wondering if a standard method exists.
That's called capitalization. Use Apache Commons's StringUtils to do that.
See more here:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
WordUtils is also worth looking at. See here
Otherwise it's a rather simple fix such as; String string1 = someString.substring(0,1).toUpperCase() + someString.substring(1);
You can put it in a function, and call it whenever you need. Saves you the trouble of maintaining libraries you don't need. (not that apache commons is ever trouble, but you get the point..)
EDIT: someString.substring(1) part can be written as someString.substring(1).toLowerCase() just to make sure that the rest of the string is in lowercase
I don't know about any direct equivalent, but you can always write one:
public static String capitalize(String input) {
if (input == null || input.length() <= 0) {
return input;
}
char[] chars = new char[1];
input.getChars(0, 1, chars, 0);
if (Character.isUpperCase(chars[0])) {
return input;
} else {
StringBuilder buffer = new StringBuilder(input.length());
buffer.append(Character.toUpperCase(chars[0]));
buffer.append(input.toCharArray(), 1, input.length()-1);
return buffer.toString();
}
}
Related
I have:
String str = "Hello, how, are, you";
I want to create a helper method that removes the commas from any string. Which of the following is more accurate?
private static String removeComma(String str){
if(str.contains(",")){
str = str.replaceAll(",","");
}
return str;
}
OR
private static String removeComma(String str){
str = str.replaceAll(",","");
return str;
}
Seems like I don't need the IF statement but there might be a case where I do.
If there is a better way let me know.
Both are functionally equivalent but the former is more verbose and will probably be slower because it runs an extra operation.
Also note that you don't need replaceAll (which accepts a regular expression): replace will do.
So I would go for:
private static String removeComma(String str){
return str.replace(",", "");
}
The IF statement is unnecessary, unless you're handling "large" strings (we're talking megabytes or more).
If you're using the IF statement, your code will first search for the first occurance of a comma, and then execute the replacement. This could be costly if the comma is near the end of the string and your string is large, since it will have to be traversed twice.
Without the IF statement, commas will be replaced if they exist. If the answer is negative, your string will be untouched.
Bottom rule: use the version without the IF statement.
Both are correct, but the second one is cleaner since the IF statement of the first alternative is not needed.
It's a matter of what is the probability to have strings with comma in your universe of strings.
If you have a high probability, call the method replaceAll without checking first.
BUT If you are not using extremely huge strings, I guess you will see no difference in perfomance at all.
Just another solution with time complexity O(n), space complexity O(n):
public static String removeComma(String str){
int length = str.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
char c = str.charAt(i);
if (c != ',') {
sb.append(c);
}
}
return sb.toString();
}
Im in highschool and this is an assignment i have, you guys are out of my league but im willing to learn and understand. I looked all over the place but all i could find was complicated syntax i dont know yet. This is what i have, it takes a String and reverses it. I managed to get it to ignore Capitals, but i cannot figure out how to make it ignore symbols. The numbers i have there are from the ANSI Characters, there is a list on textpad im using. Dont be afraid to be harsh, im not good at this and i only want to improve so have at it.
import java.util.Scanner;
public class PalindromeV2
{
public static void main(String[] args)
{
//declare
Scanner sc = new Scanner(System.in);
String fwd, rev;
String result;
//input
System.out.println("What word would you like to Palindrome test?");
fwd = sc.next();
rev = reverseString(fwd);
result = stripPunctuation(fwd);
if(stripPunctuation(rev).equals(stripPunctuation(fwd)))
{
System.out.println("That is a palindrome");
}
else
System.out.println("That is not a palindrome");
}
public static String reverseString(String fwd)
{
String rev = "";
for(int i = fwd.length()-1; i >= 0; i--)
{
rev += fwd.charAt(i);
}
return rev.toUpperCase();
}
public static String stripPunctuation(String fwd)
{
String result = "";
fwd = fwd.toUpperCase();
for(int i = fwd.length()-1; i >= 0; i--)
{
if((fwd.charAt(i)>=65 && fwd.charAt(i)<=90)||(fwd.charAt(i) >= 48 && fwd.charAt(i) <= 58));
result = result + fwd.charAt(i);
}
return result;
}
}
You can use this as a checking condition
if (Character.isLetter(fwd.charAt(i)) {
// do something
}
This will check to make sure the character is a letter, so you don't have to worry about case, numbers, or other symbols.
If you want to strip your string out of some set of characters than do something like that
clearString=targetStringForStripping.replaceAll([type_characters_for_stripping],"");
this will remove all characters you will provide inside square brackets.
There is even more. If you want to let say leave only letters (because in palindromes nothing matters except letters - spaces are not important to) than you simply can use predefine character set - letters.
To conclude all if you do
clearString=targetStringForStripping.replaceAll("[\w]","");
or
clearString=targetStringForStripping.replaceAll("[^a-zA-Z]","");
you will get clear string with white characters in first example, and only letters in second one. Perfect situation for isPalindrom resolution.
if((fwd.charAt(i)>=65 && fwd.charAt(i)<=90)||(fwd.charAt(i) >= 48 && fwd.charAt(i) <= 58));
you have semicolon at last. so i think if condition is no use here
Since this is a highschool assignment, I'll just give some pointers, you'll figure it out on your own.
Think about what you want to include / exclude, then write the code.
Keep in mind, that you can compare char variables using < or > operators as long as you do not want to handle complex character encodings.
A String is really just a sequence of chars which one by one you can compare or reorder, include or exclude.
A method should only do one thing, not a lot of things. Have a look at your reverseString method. This is doing an toUpperCase to your string at the same time. If your programs get more complex, this way of doing things is not to easy to follow.
Finally, if you e.g. just want to include capital letters in your palindrome check, then try some code like this:
char[] toCheck = fwd.toCharArray();
for (char c : toCheck) {
if (c >= 'A' && c <= 'Z') {
result = result + c;
}
}
Depending on your requirements this might do what you want. If you want something different, have a look at the hints I gave above.
Java golf?
public static String stripPunctuation(String stripThis) {
return stripThis.replaceAll("\\W", "");
}
Trying to implement contains() method without using built-in method contains().
Here is my code:
public static boolean containsCS(String str, CharSequence cs) {
//char[] chs = str.toCharArray();
boolean result = false;
int i=0;
while(i<str.length()) {
int j=0;
while(j<cs.length()) {
if(NEED TO CHECK IF THERE IS AN INDEX OUT OF BOUNDS EXCEPTION) {
result = false;
break;
}
if(str.charAt(i+j)==cs.charAt(j)) {
result|=true; //result = false or true ->>>>> which is true.
j++;
} else {
result = false;
break;
}
}
i++;
}
return false;
}
Let's say:
String str = "llpll"
Charsequence cs = "llo"
I want to make sure this method works properly in the above case where the Charsequence has one or more char to check but the String runs out length. How should I write the first if statement?
if (i+cs.length() > str.length()){
OUT OF BOUNDS
}
Well if it were me first thing I'd check is that the length of my char sequence was <= to the length of my string.
As soon as you chop that logic path out.
If the lengths are equal you can just use ==
Then it would occur that if you chopped up str
into cs length parts, you could do a straight comparison there as well.
e.g str of TonyJ and search for a three character sequence would pile through
Ton
ony
nyJ
One loop, one if statement and a heck of a lot clearer.
I would suggest using this and using the contains method therein.
Edit - For the reading impaired:
The linked method is not from java.lang.String or java.lang.Object
If you'd bother to actually look at the links, you would see that it is the Apache Commons-Lang API and the StringUtils.contains(...) method that I reference, which very clearly answers the question.
If this is for your homework, which I suspect it is, then I suggest you take a look at the API for the String class to see what other methods are available to help find the location of one String within another.
Also consider looking at the source code for String to see how it implements it.
I'm sure you already know this, but it is in fact possible to see the actual source code of the built-in classes and methods. So I'd take a look there for a start. The String class is especially interesting, IMO.
I need to trim a String in java so that:
The quick brown fox jumps over the laz dog.
becomes
The quick brown...
In the example above, I'm trimming to 12 characters. If I just use substring I would get:
The quick br...
I already have a method for doing this using substring, but I wanted to know what is the fastest (most efficient) way to do this because a page may have many trim operations.
The only way I can think off is to split the string on spaces and put it back together until its length passes the given length. Is there an other way? Perhaps a more efficient way in which I can use the same method to do a "soft" trim where I preserve the last word (as shown in the example above) and a hard trim which is pretty much a substring.
Thanks,
Below is a method I use to trim long strings in my webapps.
The "soft" boolean as you put it, if set to true will preserve the last word.
This is the most concise way of doing it that I could come up with that uses a StringBuffer which is a lot more efficient than recreating a string which is immutable.
public static String trimString(String string, int length, boolean soft) {
if(string == null || string.trim().isEmpty()){
return string;
}
StringBuffer sb = new StringBuffer(string);
int actualLength = length - 3;
if(sb.length() > actualLength){
// -3 because we add 3 dots at the end. Returned string length has to be length including the dots.
if(!soft)
return escapeHtml(sb.insert(actualLength, "...").substring(0, actualLength+3));
else {
int endIndex = sb.indexOf(" ",actualLength);
return escapeHtml(sb.insert(endIndex,"...").substring(0, endIndex+3));
}
}
return string;
}
Update
I've changed the code so that the ... is appended in the StringBuffer, this is to prevent needless creations of String implicitly which is slow and wasteful.
Note: escapeHtml is a static import from apache commons:
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
You can remove it and the code should work the same.
Here is a simple, regex-based, 1-line solution:
str.replaceAll("(?<=.{12})\\b.*", "..."); // How easy was that!? :)
Explanation:
(?<=.{12}) is a negative look behind, which asserts that there are at least 12 characters to the left of the match, but it is a non-capturing (ie zero-width) match
\b.* matches the first word boundary (after at least 12 characters - above) to the end
This is replaced with "..."
Here's a test:
public static void main(String[] args) {
String input = "The quick brown fox jumps over the lazy dog.";
String trimmed = input.replaceAll("(?<=.{12})\\b.*", "...");
System.out.println(trimmed);
}
Output:
The quick brown...
If performance is an issue, pre-compile the regex for an approximately 5x speed up (YMMV) by compiling it once:
static Pattern pattern = Pattern.compile("(?<=.{12})\\b.*");
and reusing it:
String trimmed = pattern.matcher(input).replaceAll("...");
Please try following code:
private String trim(String src, int size) {
if (src.length() <= size) return src;
int pos = src.lastIndexOf(" ", size - 3);
if (pos < 0) return src.substring(0, size);
return src.substring(0, pos) + "...";
}
Try searching for the last occurence of a space that is in a position less or more than 11 and trim the string there, by adding "...".
Your requirements aren't clear. If you have trouble articulating them in a natural language, it's no surprise that they'll be difficult to translate into a computer language like Java.
"preserve the last word" implies that the algorithm will know what a "word" is, so you'll have to tell it that first. The split is a way to do it. A scanner/parser with a grammar is another.
I'd worry about making it work before I concerned myself with efficiency. Make it work, measure it, then see what you can do about performance. Everything else is speculation without data.
How about:
mystring = mystring.replaceAll("^(.{12}.*?)\b.*$", "$1...");
I use this hack : suppose that the trimmed string must have 120 of length :
String textToDisplay = textToTrim.substring(0,(textToTrim.length() > 120) ? 120 : textToTrim.length());
if (textToDisplay.lastIndexOf(' ') != textToDisplay.length() &&textToDisplay.length()!=textToTrim().length()) {
textToDisplay = textToDisplay + textToTrim.substring(textToDisplay.length(),textToTrim.indexOf(" ", textToDisplay.length()-1))+ " ...";
}
Basically given an int, I need to generate a String with the same length containing only the specified character. Related question here, but it relates to C# and it does matter what's in the String.
This question, and my answer to it are why I am asking this one. I'm not sure what's the best way to go about it performance wise.
Example
Method signature:
String getPattern(int length, char character);
Usage:
//returns "zzzzzz"
getPattern(6, 'z');
What I've tried
String getPattern(int length, char character) {
String result = "";
for (int i = 0; i < length; i++) {
result += character;
}
return result;
}
Is this the best that I can do performance-wise?
You should use StringBuilder instead of concatenating chars this way. Use StringBuilder.append().
StringBuilder will give you better performance. The problem with concatenation the way you are doing is each time a new String (string is immutable) is created then the old string is copied, the new string is appended, and the old String is thrown away. It's a lot of extra work that over a period of type (like in a big for loop) will cause performance degradation.
StringUtils from commons-lang or Strings from guava are your friends. As already stated avoid String concatenations.
StringUtils.repeat("a", 3) // => "aaa"
Strings.repeat("hey", 3) // => "heyheyhey"
Use primitive char arrays & some standard util classes like Arrays
public class Test {
static String getPattern(int length, char character) {
char[] cArray = new char[length];
Arrays.fill(cArray, character);
// return Arrays.toString(cArray);
return new String(cArray);
}
static String buildPattern(int length, char character) {
StringBuilder sb= new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(character);
}
return sb.toString();
}
public static void main(String args[]){
long time = System.currentTimeMillis();
getPattern(10000000,'c');
time = System.currentTimeMillis() - time;
System.out.println(time); //prints 93
time = System.currentTimeMillis();
buildPattern(10000000,'c');
time = System.currentTimeMillis() - time;
System.out.println(time); //prints 188
}
}
EDIT Arrays.toString() gave lower performance since it eventually used a StringBuilder, but the new String did the magic.
Yikes, no.
A String is immutable in java; you can't change it. When you say:
result += character;
You're creating a new String every time.
You want to use a StringBuilder and append to it, then return a String with its toString() method.
I think it would be more efficient to do it like following,
String getPattern(int length, char character)
{
char[] list = new char[length];
for(int i =0;i<length;i++)
{
list[i] = character;
}
return new string(list);
}
Concatenating a String is never the most efficient, since String is immutable, for better performance you should use StringBuilder, and append()
String getPattern(int length, char character) {
StringBuilder sb= new StringBuilder(length)
for (int i = 0; i < length; i++) {
sb.append(character);
}
return sb.toString();
}
Performance-wise, I think you'd have better results creating a small String and concatenating (using StringBuilder of course) until you reach the request size: concatenating/appending "zzz" to "zzz" performs probably betters than concatenating 'z' three times (well, maybe not for such small numbers, but when you reach 100 or so chars, doing ten concatenations of 'z' followed by ten concatenations of "zzzzzzzzzz" is probably better than 100 concatenatinos of 'z').
Also, because you ask about GWT, results will vary a lot between DevMode (pure Java) and "production mode" (running in JS in the browser), and is likely to vary depending on the browser.
The only way to really know is to benchmark, everything else is pure speculation.
And possibly use deferred binding to use the most performing variant in each browser (that's exactly how StringBuilder is emulated in GWT).