I have got a String which reads "You cannot sit on that " + entity.getEntityType().toLowerCase() + "!";. Which returns an upper case, which is why I convert it to lower case.
However, how can I get the first letter ONLY, and turn it into an upper case?
A one-liner solution would be preferred, however beggars cant be choosers.
In java, if you do any manipulation to String, it will create a new string in the memory.
Here's, how to do it:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
It's more efficient to treat the first character what it is - a character and not a String:
String output = Character.toUpperCase(input.charAt(0)) + input.substring(1);
The first thing it came to my mind was this
int x = a.codePointAt(0)-32;
a=a.replace(a.charAt(0), (char) x);
You can just use something like this:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
On the other hand is isn't bad to take a look at the guava libraries.
String output = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, entity.getEntityType()));
For this case only it will be overkill but it has a lot of other usefull utilities (Not only for String manipulation)
Related
I know how to do it... but the way I'm thinking is complicated and has a lot of room for errors. I'm still learning Java, but I have learned that Java has ways of doing just about anything. Is there some way I can put parentheses around each occurrence of a substring? (see an example below)
Original String: "abcabcabcd"
Search For: "abc"
Final Output: "(abc)(abc)(abc)d"
The easiest way here is to use String::replaceAll
String str = "abcabcabcd";
String sub = "abc";
System.out.println(str.replaceAll(sub, "(" + sub + ")"));
As pointed out by #Jacob G., String::replace may be preferred here because there is no regex element needed.
Output:
(abc)(abc)(abc)d
If you are interested in another solution, there is one with recursion. Just for educational purpose:
private static String parentheses(String input, String template) {
int start = input.indexOf(template);
if (start == -1) {
return input;
}
return input.substring(0, start) +
"(" + input.substring(start, start + template.length()) + ")" +
parentheses(input.substring(start + template.length()), template);
}
I try to replace ". " with "\n\n" within a string but it doesnt work, I use the following code:
text=text.replace(". ","\n\n");
The result is every word without the last letter of the word in a each line. I read something like the point means any character in this case, but how can I actually refer to the point?
Input Example: "Hello world"
Example of the output:
Hell
world
Thank you
There is something fishy here; either text is not a String, or you don't use .replace() but something else (.replaceAll()?), or Android's .replace() is buggy.
And I frankly doubt that Android devs would have had such an overlook.
The Javadoc for String#replace() says:
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. [emphasis mine]
Unlike its sibling methods (.replaceFirst() and .replaceAll()) which do use regexes, .replace() doesn't (and the fact that internally it does use Pattern, at least in Oracle's JDK [*], is not the problem).
Therefore, if you actually use .replace() and gain the result you say, this is a bug in Android. If this is the case, try an alternative, like so (UNTESTED):
public static String realStringReplace(final String victim, final String target,
final String replacement)
{
final int skip = target.length();
final StringBuilder sb = new StringBuilder(victim.length());
String tmp = victim;
int index;
while (!tmp.isEmpty()) {
index = tmp.indexOf(target);
if (index == -1)
break;
sb.append(tmp.subString(0, index)).append(replacement);
tmp = tmp.subString(index + skip);
}
return sb.append(tmp).toString();
}
the point means any character if you use
text=text.replaceAll(". ", "\n\n");
perhaps you have posted the wrong code, in this case try this one:
text=text.replaceAll("\\. ", "\n\n");
the strange thing is that this line is equivalent to the line that you have posted..
Im trying to find a word in a string. However, due to a period it fails to recognize one word. Im trying to remove punctuation, however it seems to have no effect. Am I missing something here? This is the line of code I am using: s.replaceAll("([a-z] +) [?:!.,;]*","$1");
String test = "This is a line about testing tests. Tests are used to examine stuff";
String key = "tests";
int counter = 0;
String[] testArray = test.toLowerCase().split(" ");
for(String s : testArray)
{
s.replaceAll("([a-z] +) [?:!.,;]*","$1");
System.out.println(s);
if(s.equals(key))
{
System.out.println(key + " FOUND");
counter++;
}
}
System.out.println(key + " has been found " + counter + " times.");
}
I managed to find a solution (though may not be ideal) through using s = s.replaceAll("\W",""); Thanks for everyones guidance on how to solve this problem.
You could also take advantage of the regex in the split operation. Try this:
String[] testArray = test.toLowerCase().split("\\W+");
This will split on apostrophe, so you may need to tweak it a bit with a specific list of characters.
Strings are immutable. You would need assign the result of replaceAll to the new String:
s = s.replaceAll("([a-z] +)*[?:!.,;]*", "$1");
^
Also your regex requires that a space exist between the word and the the punctuation. In the case of tests., this isn't true. You can adjust you regex with an optional (zero or more) character to account for this.
Your regex doesn't seem to work as you want.
If you want to find something which has period after that then this will work
([a-z]*) [?(:!.,;)*]
it returns "tests." when it's run on your given string.
Also
[?(:!.,;)*]
just points out the punctuation which will then can be replaced.
However I am not sure why you are not using substring() function.
Pretty basic question for someone who knows.
Instead of getting from
"This is my text.
And here is a new line"
To:
"This is my text. And here is a new line"
I get:
"This is my text.And here is a new line.
Any idea why?
L.replaceAll("[\\\t|\\\n|\\\r]","\\\s");
I think I found the culprit.
On the next line I do the following:
L.replaceAll( "[^a-zA-Z0-9|^!|^?|^.|^\\s]", "");
And this seems to be causing my issue.
Any idea why?
I am obviously trying to do the following: remove all non-chars, and remove all new lines.
\s is a shortcut for whitespace characters in regex. It has no meaning in a string. ==> You can't use it in your replacement string. There you need to put exactly the character(s) that you want to insert. If this is a space just use " " as replacement.
The other thing is: Why do you use 3 backslashes as escape sequence? Two are enough in Java. And you don't need a | (alternation operator) in a character class.
L.replaceAll("[\\t\\n\\r]+"," ");
Remark
L is not changed. If you want to have a result you need to do
String result = L.replaceAll("[\\t\\n\\r]+"," ");
Test code:
String in = "This is my text.\n\nAnd here is a new line";
System.out.println(in);
String out = in.replaceAll("[\\t\\n\\r]+"," ");
System.out.println(out);
The new line separator is different for different OS-es - '\r\n' for Windows and '\n' for Linux.
To be safe, you can use regex pattern \R - the linebreak matcher introduced with Java 8:
String inlinedText = text.replaceAll("\\R", " ");
Try
L.replaceAll("(\\t|\\r?\\n)+", " ");
Depending on the system a linefeed is either \r\n or just \n.
I found this.
String newString = string.replaceAll("\n", " ");
Although, as you have a double line, you will get a double space. I guess you could then do another replace all to replace double spaces with a single one.
If that doesn't work try doing:
string.replaceAll(System.getProperty("line.separator"), " ");
If I create lines in "string" by using "\n" I had to use "\n" in the regex. If I used System.getProperty() I had to use that.
Your regex is good altough I would replace it with the empty string
String resultString = subjectString.replaceAll("[\t\n\r]", "");
You expect a space between "text." and "And" right?
I get that space when I try the regex by copying your sample
"This is my text. "
So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.
You May use first split and rejoin it using white space.
it will work sure.
String[] Larray = L.split("[\\n]+");
L = "";
for(int i = 0; i<Larray.lengh; i++){
L = L+" "+Larray[i];
}
This should take care of space, tab and newline:
data = data.replaceAll("[ \t\n\r]*", " ");
I'm trying to use regex to find a particular starting character and then getting the rest of the text on that particular line.
For example the text can be like ...
V: mid-voice
T: tempo
I want to use regex to grab "V:" and the the text behind it.
Is there any good, quick way to do this using regular expressions?
If your starting character were fixed, you would create a pattern like:
Pattern vToEndOfLine = Pattern.compile("(V:[^\\n]*)")
and use find() rather than matches().
If your starting character is dynamic, you can always write a method to return the desired pattern:
Pattern getTailOfLinePatternFor(String start) {
return Pattern.compile("(" + start + "[^\\n]*");
}
These can be worked on a little bit depending on your needs.
For a pattern match try for your example:
V:.*$
Here's the best, cleanest and easiest (ie one-line) way:
String[] parts = str.split("(?<=^\\w+): ");
Explanation:
The regex uses a positive look behind to break on the ": " after the first word (in this case "V") and capture both halves.
Here's a test:
String str = "V: mid-voice T: tempo";
String[] parts = str.split("(?<=^\\w+): ");
System.out.println("key = " + parts[0] + "\nvalue = " + parts[1]);
Output:
key = V
value = mid-voice T: tempo