First char to upper case [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to upper case every first letter of word in a string?
Most efficient way to make the first character of a String lower case?
I want to convert the first letter of a string to upper case. I am attempting to use replaceFirst() as described in JavaDocs, but I have no idea what is meant by regular expression.
Here is the code I have tried so far:
public static String cap1stChar(String userIdea)
{
String betterIdea, userIdeaUC;
char char1;
userIdeaUC = userIdea.toUpperCase();
char1 = userIdeaUC.charAt(0);
betterIdea = userIdea.replaceFirst(char1);
return betterIdea;
}//end cap1stChar
The compiler error is that the argument lists differ in lengths. I presume that is because the regex is missing, however I don't know what that is exactly.

Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.
What replaceFirst() does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.
What you want to do is convert the string to an array using the String class' charAt() method, and then use Character.toUpperCase() to change the character to upper case (obviously). Your code would look like this:
char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);
Or, if you feel comfortable with more complex, one-lined java code:
betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);
Both of these do the same thing, which is converting the first character of userIdea to an upper case character.

Or you can do
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);

public static String cap1stChar(String userIdea)
{
char[] stringArray = userIdea.toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
return userIdea = new String(stringArray);
}

Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.
Try this.
betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())

String toCamelCase(String string) {
StringBuffer sb = new StringBuffer(string);
sb.replace(0, 1, string.substring(0, 1).toUpperCase());
return sb.toString();
}

userIdeaUC = userIdea.substring(0, 1).toUpperCase() + userIdea.length() > 1 ? userIdea.substring(1) : "";
or
userIdeaUC = userIdea.substring(0, 1).toUpperCase();
if(userIdea.length() > 1)
userIdeaUC += userIdea.substring(1);

For completeness, if you wanted to use replaceFirst, try this:
public static String cap1stChar(String userIdea)
{
String betterIdea = userIdea;
if (userIdea.length() > 0)
{
String first = userIdea.substring(0,1);
betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
}
return betterIdea;
}//end cap1stChar

Related

Converting and storing integers to ASCII Characters [duplicate]

How do you concatenate characters in java? Concatenating strings would only require a + between the strings, but concatenating chars using + will change the value of the char into ascii and hence giving a numerical output. I want to do System.out.println(char1+char2+char3... and create a String word like this.
I could do
System.out.print(char1);
System.out.print(char2);
System.out.print(char3);
But, this will only get me the characters in 1 line. I need it as a string. Any help would be appreciated.
Thanks
Do you want to make a string out of them?
String s = new StringBuilder().append(char1).append(char2).append(char3).toString();
Note that
String b = "b";
String s = "a" + b + "c";
Actually compiles to
String s = new StringBuilder("a").append(b).append("c").toString();
Edit: as litb pointed out, you can also do this:
"" + char1 + char2 + char3;
That compiles to the following:
new StringBuilder().append("").append(c).append(c1).append(c2).toString();
Edit (2): Corrected string append comparison since, as cletus points out, a series of strings is handled by the compiler.
The purpose of the above is to illustrate what the compiler does, not to tell you what you should do.
I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:
String a = "a" + "b" + "c";
String b = System.getProperty("blah") + "b";
The first is evaluated at compile-time. The second is evaluated at run-time.
So never replace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.
If the characters are constant, this is fine:
String s = "" + 'a' + 'b' + 'c';
If however they aren't, consider this:
String concat(char... chars) {
if (chars.length == 0) {
return "";
}
StringBuilder s = new StringBuilder(chars.length);
for (char c : chars) {
s.append(c);
}
return s.toString();
}
as an appropriate solution.
However some might be tempted to optimise:
String s = "Name: '" + name + "'"; // String name;
into this:
String s = new StringBuilder().append("Name: ").append(name).append("'").toString();
While this is well-intentioned, the bottom line is DON'T.
Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.
For low-level optimisation the compiler is better at optimising code than you are.
Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.
If you have a bunch of chars and want to concat them into a string, why not do
System.out.println("" + char1 + char2 + char3);
?
You can use the String constructor.
System.out.println(new String(new char[]{a,b,c}));
You need to tell the compiler you want to do String concatenation by starting the sequence with a string, even an empty one. Like so:
System.out.println("" + char1 + char2 + char3...);
System.out.println(char1+""+char2+char3)
or
String s = char1+""+char2+char3;
You need a String object of some description to hold your array of concatenated chars, since the char type will hold only a single character. e.g.,
StringBuilder sb = new StringBuilder('a').append('b').append('c');
System.out.println(sb.toString);
public class initials {
public static void main (String [] args) {
char initialA = 'M';
char initialB = 'P';
char initialC = 'T';
System.out.println("" + initialA + initialB + initialC );
}
}
I don't really consider myself a Java programmer, but just thought I'd add it here "for completeness"; using the (C-inspired) String.format static method:
String s = String.format("%s%s", 'a', 'b'); // s is "ab"
this is very simple approach to concatenate or append the character
StringBuilder desc = new StringBuilder();
String Description="this is my land";
desc=desc.append(Description.charAt(i));
simple example to selecting character from string and appending to string variable
private static String findaccountnum(String holdername, String mobile) {
char n1=holdername.charAt(0);
char n2=holdername.charAt(1);
char n3=holdername.charAt(2);
char n4=mobile.charAt(0);
char n5=mobile.charAt(1);
char n6=mobile.charAt(2);
String number=new StringBuilder().append(n1).append(n2).append(n3).append(n4).append(n5).append(n6).toString();
return number;
}
System.out.print(a + "" + b + "" + c);

How to - Loop through a String and identify a specific character and add to the string

I'm currently trying to loop through a String and identity a specific character within that string then add a specific character following on from the originally identified character.
For example using the string: aaaabbbcbbcbb
And the character I want to identify being: c
So every time a c is detected a following c will be added to the string and the loop will continue.
Thus aaaabbbcbbcbb will become aaaabbbccbbccbb.
I've been trying to make use of indexOf(),substring and charAt() but I'm currently either overriding other characters with a c or only detecting one c.
I know you've asked for a loop, but won't something as simple as a replace suffice?
String inputString = "aaaabbbcbbcbb";
String charToDouble = "c";
String result = inputString.replace(charToDouble, charToDouble+charToDouble);
// or `charToDouble+charToDouble` could be `charToDouble.repeat(2)` in JDK 11+
Try it online.
If you insist on using a loop however:
String inputString = "aaaabbbcbbcbb";
char charToDouble = 'c';
String result = "";
for(char c : inputString.toCharArray()){
result += c;
if(c == charToDouble){
result += c;
}
}
Try it online.
Iterate over all the characters. Add each one to a StringBuilder. If it matches the character you're looking for then add it again.
final String test = "aaaabbbcbbcbb";
final char searchChar = 'c';
final StringBuilder builder = new StringBuilder();
for (final char c : test.toCharArray())
{
builder.append(c);
if (c == searchChar)
{
builder.append(c);
}
}
System.out.println(builder.toString());
Output
aaaabbbccbbccbb
You probably are trying to modify a String in java. Strings in Java are immutable and cannot be changed like one might do in c++.
You can use StringBuilder to insert characters. eg:
StringBuilder builder = new StringBuilder("acb");
builder.insert(1, 'c');
The previous answer suggesting String.replace is the best solution, but if you need to do it some other way (e.g. for an exercise), then here's a 'modern' solution:
public static void main(String[] args) {
final String inputString = "aaaabbbcbbcbb";
final int charToDouble = 'c'; // A Unicode codepoint
final String result = inputString.codePoints()
.flatMap(c -> c == charToDouble ? IntStream.of(c, c) : IntStream.of(c))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
assert result.equals("aaaabbbccbbccbb");
}
This looks at each character in turn (in an IntStream). It doubles the character if it matches the target. It then accumulates each character in a StringBuilder.
A micro-optimization can be made to pre-allocate the StringBuilder's capacity. We know the maximum possible size of the new string is double the old string, so StringBuilder::new can be replaced by () -> new StringBuilder(inputString.length()*2). However, I'm not sure if it's worth the sacrifice in readability.

Java 8, updating element in array [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have trouble with my code. I need to replace element in Array if condition is true.
Inputs are:
dashedCapital = "------";
input = "a";
capital = "Warsaw";
Code should check if capital contains input and if yes replace "-" in dashedCapital to character from input at specified position:
public static String changeDashedCapital(String dashedCapital, String input, String capital){
String[] capitalArray = capital.split("");
String[] dashedCapitalArray = dashedCapital.split("");
String[] character = input.split("");
for(int i = 0; i < capitalArray.length; i++){
//System.out.println(i);
//System.out.println(capitalArray[i] + character[0] + dashedCapitalArray[i]);
if(capitalArray[i] == character[0]){
dashedCapitalArray[i] = character[0];
}
}
String result = Arrays.toString(dashedCapitalArray);
System.out.println(result);
return result;
}
Result is "------" but should be "-a--a-". What's going wrong?
John, thanks for your reply, it was helpful.
I edited my method so it's look like this now:
public static String changeDashedCapital(String dashedCapital, String input, String capital){
for(int i = 0; i < capital.length(); i++){
if(capital.charAt(i).equals(input.charAt(0))) {
String new_dashed = dashedCapital.substring(0,i)+input.charAt(0)+dashedCapital.substring(i);
System.out.println(new_dashed);
}
}
return "OK:";
Now i get this error:
GetWord.java:69: error: char cannot be dereferenced
if(capital.charAt(i).equals(input.charAt(0))) {
^
1 error
I don't understand why it's wrong. I using a equals() function. I also tried "==" operator but then nothing happens. What does it mean "char cannot be dereferenced"? How I could compare single chars from string with another chars from another string?
The reason it is not working is because your if for character equality is never true. You’re comparing strings of length 1 and not characters. You can quickly fix by changing if be using the string comparing function .equals()
if(capitalArray[i].equals(character[0])){
...
}
However, you should change your code and not just use this fix. Don’t split your stings into arrays, just use the .charAt() method to get a character at a particular index.

Remove n number of dot(.) from String in Java [duplicate]

This question already has answers here:
Trim leading or trailing characters from a string?
(6 answers)
Closed 5 years ago.
I have the following string and I want to remove dynamic number of dot(.) at the end of the String.
"abc....."
Dot(.) can be more than one
Try this. It uses a regular expression to replace all dots at the end of your string with empty strings.
yourString.replaceAll("\\.+$", "");
Could do this to remove all .:
String a = "abc.....";
String new = a.replaceAll("[.]", "");
Remove just the trailing .'s:
String new = a.replaceAll("//.+$","");
Edit: Seeing the comment. To remove last n .'s
int dotsToRemove = 5; // whatever value n
String new = a.substring(0, s.length()-dotsToRemove);
how about using this function? seems to work faster than regex
public static String trimPoints(String txt)
{
char[] cs = txt.toCharArray();
int index =0;
for(int x =cs.length-1;x>=0;x--)
{
if(cs[x]=='.')
continue;
else
{
index = x+1;
break;
}
}
return txt.substring(0,index);
}

Parsing Java String type Error

What i'm trying to do is incorporate interface methods to complete a task given the variables inside of a string. The string i'm given, "s" can be made up numbers, +, -, and * symbols. The integer return is fairly easy as all i'm doing is returning an integer interface method of that int. However, for the other 3 symbols, I need to recursively incorporate a method to find the left and right nodes. I've posted my code below...
public static Expression parseString( String s ) {
String[] parse = s.split("\\s+");
String[] parsecopy;
Expression exp1;
Expression exp2;
if(s == null) {
return null;
}
if(parse[0].equals("+")) {
exp1 = parseString(parse[0]);
parsecopy = Arrays.copyOfRange(parse, 2, parse.length);
exp2 = parseString(parsecopy);
return new AddExpression(exp1, exp2);
}
else if() {
The problem - So my code creates a copy of the original string to find the next item in that string. I do this by using the Array function, copyOfRange(). However, when I want to call exp2 = parseString(parsecopy), i'm receiving an error because parseString takes in a string argument which has to be of the type String[]. The reason i'm trying to get parsecopy instead of parsecopy[0] is because parsecopy wouldn't create an endless loop and I would actually be able to iterate through the string.
Error code - The method parseString(String) in the type Parse is not applicable for the arguments (String[])
if(parse[0].equals("+")) {
exp1 = parseString(parse[0]);
parsecopy = Arrays.copyOfRange(parse, 2, parse.length);
exp2 = parseString(parsecopy);
return new AddExpression(exp1, exp2);
}
exp1 = parseString(parse[0]);
you are doing recursive calling here.
Since the parameter you pass to split is a regex, you can simply do:
String[] ss = "12121+34234 *23423 -123123 *123123-12312+1231231-123123".split("\\s?[\\+\\-\\*]\\s?");
this way you split your string wherever you got a +, - , or * (possibly with a whitespace after or before).
And please do the null-check of the string before split it :D
Hope it helps.
It seems like you want to check parse[1] equals "+" rather than parse[0].
You would expect 1 + 2 rather than + 1 2.

Categories