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);
Related
Is it possible to replace digits in a String with that amount of a certain character like 'X' using a regex? (I.e. replace "test3something8" with "testXXXsomethingXXXXXXXX")?
I know I could use a for-loop, but I'm looking for an as short-as-possible (regex) one-liner solution (regarding a code-golf challenge - and yes, I am aware of the codegolf-SE, but this is a general Java question instead of a codegolf question).
I know how to replace digits with one character:
String str = "test3something8".replaceAll("[1-9]", "X"); -> str = "testXsomethingX"
I know how to use groups, in case you want to use the match, or add something after every match instead of replacing it:
String str = "test3something8".replaceAll("([1-9])", "$1X"); -> str = "test3Xsomething8X"
I know how to create n amount of a certain character:
int n = 5; String str = new String(new char[n]).replace('\0', 'X'); -> str = "XXXXX"
Or like this:
int n = 5; String str = String.format("%1$"+n+"s", "").replace(' ', 'X'); -> str = "XXXXX";
What I want is something like this (the code below obviously doesn't work, but it should give an idea of what I somehow want to achieve - preferably even a lot shorter):
String str = "test3Xsomething8X"
.replaceAll("([1-9])", new String(new char[new Integer("$1")]).replace('\0', 'X')));
// Result I want it to have: str = "testXXXsomethingXXXXXXXX"
As I said, this above doesn't work because "$1" should be used directly, so now it's giving a
java.lang.NumberFormatException: For input string: "$1"
TL;DR: Does anyone know a one-liner to replace a digit in a String with that amount of a certain character?
If you really want to have it as a one-liner. A possible solution (see it more as a PoC) could be to use the Stream API.
String input = "test3something8";
input.chars()
.mapToObj(
i -> i >= '0' && i <= '9' ?
new String(new char[i-'0']).replace('\0', 'X')
: "" + ((char)i)
)
.forEach(System.out::print);
output
testXXXsomethingXXXXXXXX
note No investigation has been done for performance, scalability, to be GC friendly, etc.
Can't figure out how to replace a string with a character in Java. I wanted a function like this:
replace(string, char)
but there's not a function like this in Java.
String str = str.replace("word", '\u0082');
String str = str.replace("word", (char)130);
How do I go about this?
Use a string as the replacement that happens to be only a single character in length:
String original = "words";
String replaced = original.replace("word", "\u0130");
The replaced instance will be equivalent to "İs".
Note also that, from your question, '\u0130' and (char)130 are not the same characters. The \u syntax uses hexadecimal and your cast is using decimal notation.
Very simply:
String orginal = "asdf";
char replacement = 'z';
orginal = original.replace(original, replacement+"");
You asked for a "function" in Java, you can allways create a method like this
public static String replace (String text, char old, char n){
return text.replace(old, n);
}
Then you can call this method as you want
String a = replace("ae", 'e', '3');
In this case the method will return a String with a3 as value, but you can replace not only a char by another, you can replace a String with multiple characters in the same way
public static String replace (String text, String old, String n){
return text.replace(old, n);
}
Then you call this method like this
String a = replace("aes", "es", "rmy");
The result will be a String with army as value
the simplest way:
"value_".replace("_",String.valueOf((char)58 )); //return "value:"
EDIT:
(char)58 //return: ':'
(int)':' //return: 58
Since we want to work with codes and no character we have to pass code to character
another problem to solve is that method "replace" does not take "(String x,char y)"
So we pass our character to String this way:
String.valueOf((char)58) //this is a String like this ":"
Finally we have String from int code, to be replaced.
"String is a sequence of characters"
String s="hello";
char c='Y';
System.out.println(s.replace(s, Character.toString(c)));
Output:
Y
so i have to write a java code to :
Input a name
Format name in title case
Input second name
Format name in title case
Display them in alphabet order
i know that The Java Character class has the methods isLowerCase(), isUpperCase, toLowerCase() and toUpperCase(), which you can use in reviewing a string, character by character. If the first character is lowercase, convert it to uppercase, and for each succeeding character, if the character is uppercase, convert it to lowercase.
the question is how i check each letter ?
what kind of variables and strings should it be contained ?
can you please help?
You should use StringBuilder, whenver dealing with String manipulation.. This way, you end up creating lesser number of objects..
StringBuilder s1 = new StringBuilder("rohit");
StringBuilder s2 = new StringBuilder("jain");
s1.replace(0, s1.length(), s1.toString().toLowerCase());
s2.replace(0, s2.length(), s2.toString().toLowerCase());
s1.setCharAt(0, Character.toTitleCase(s1.charAt(0)));
s2.setCharAt(0, Character.toTitleCase(s2.charAt(0)));
if (s1.toString().compareTo(s2.toString()) >= 0) {
System.out.println(s2 + " " + s1);
} else {
System.out.println(s1 + " " + s2);
}
You can convert the first character to uppercase, and then lowercase the remainder of the string:
String name = "jOhN";
name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
System.out.println(name); // John
For traversing Strings using only the String class, iterate through each character in a string.
String s = "tester";
int size = s.length(); // length() is the number of characters in the string
for( int i = 0; i < size; i++) {
// s.charAt(i) gets the character at the ith code point.
}
This question answers how to "change" a String - you can't. The StringBuilder class provides convenient methods for editing characters at specific indices though.
It looks like you want to make sure all names are properly capitalized, e.g.: "martin ye" -> "Martin Ye" , in which case you'll want to traverse the String input to make sure the first character of the String and characters after a space are capitalized.
For alphabetizing a List, I suggest storing all inputted names to an ArrayList or some other Collections object, creating a Comparator that implements Comparator, and passing that to Collections.sort()... see this question on Comparable vs Comparator.
This should fix it
List<String> nameList = new ArrayList<String>();
nameList.add(titleCase("john smith"));
nameList.add(titleCase("tom cruise"));
nameList.add(titleCase("johnsmith"));
Collections.sort(nameList);
for (String name : nameList) {
System.out.println("name=" + name);
}
public static String titleCase(String realName) {
String space = " ";
String[] names = realName.split(space);
StringBuilder b = new StringBuilder();
for (String name : names) {
if (name == null || name.isEmpty()) {
b.append(space);
continue;
}
b.append(name.substring(0, 1).toUpperCase())
.append(name.substring(1).toLowerCase())
.append(space);
}
return b.toString();
}
String has a method toCharArray that returns a newly allocated char[] of its characters. Remember that while Strings are immutable, elements of arrays can be reassigned.
Similarly, String has a constructor that takes a char[] representing the characters of the newly created String.
So combining these, you have one way to get from a String to a char[], modify the char[], and back to a new String.
This can be achieved in any number of ways, most of which will come down to the details of the requirements.
But the basic premise is the same. String is immutable (it's contents can not be changed), so you need away to extract the characters of the String, convert the first character to upper case and reconstitute a new String from the char array.
As has already been pointed out, this is relative simple.
The other thing you might need to do, is handle multiple names (first, last) in a single pass. Again, this is relatively simple. The difficult part is when you might need to split a string on multiple conditions, then you'll need to resort to a regular expression.
Here's a very simple example.
String name = "this is a test";
String[] parts = name.split(" ");
StringBuilder sb = new StringBuilder(64);
for (String part : parts) {
char[] chars = part.toLowerCase().toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
sb.append(new String(chars)).append(" ");
}
name = sb.toString().trim();
System.out.println(name);
I have a small problem with the minus operation in java. When the user press the 'backspace' key, I want the char the user typed, to be taken away from the word which exists.
e.g
word = myname
and after one backspace
word = mynam
This is kinda of what I have:
String sentence = "";
char c = evt.getKeyChar();
if(c == '\b') {
sentence = sentence - c;
} else {
sentence = sentence + c;
}
The add operation works. So if I add a letter, it adds to the existing word. However, the minus isn't working. Am I missing something here? Or doing it completely wrong?
Strings don’t have any kind of character subtraction that corresponds to concatenation with the + operator. You need to take a substring from the start of the string to one before the end, instead; that’s the entire string except for the last character. So:
sentence = sentence.substring(0, sentence.length() - 1);
For convenience, Java supports string concatenation with the '+' sign. This is the one binary operator with a class type as an operand. See String concatenation operator in the Java Language Specification.
Java does not support an overload of the '-' operator between a String and a char.
Instead, you can remove a character from a string by adding the substrings before and after.
sentance = sentance.substring(0, sentance.length() - 1);
There is no corresponding operator to + which allows you to delete a character from a String.
You should investigate the StringBuilder class, eg:
StringBuilder sentence = new StringBuilder();
Then you can do something like:
sentence.append(a);
for a new character or
sentence.deleteCharAt(sentence.length() - 1);
Then when you actually want to use the string, use:
String s = sentence.toString();
Is there a difference between concatenating strings with '' and ""?
For example, what is the difference between:
String s = "hello" + "/" + "world";
and
String s = "hello" + '/' + "world";
Literals enclosed in double quotes, e.g. "foo", are strings, whereas single-quoted literals, e.g. 'c', are chars. In terms of concatenation behaviour, there'll be no discernible difference.
Nevertheless, it's worth remembering that strings and chars aren't interchangeable in all scenarios, and you can't have a single-quoted string made up of multiple characters.
System.out.println('a'+'b'+'c');
> 294
System.out.println("a"+"b"+"c");
> abc
What's happening here is that (char)+(char)=(int)
In other words. Use "" for text to avoid surprises.
"." is a String, '.' is a char.
You may just look into the JDK :-)
Given two functions:
public static String concatString(String cs) {
return "hello" + cs + "world";
}
public static String concatChar(char cc) {
return "hello" + cc + "world";
}
after examination of the bytecode it boils down to two AbstractStringBuilder.append(String) vs. AbstractStringBuilder.append(char).
Both methods invoke AbstractStringBuilder.expandCapacity(int)) which will allocate a new char[] eventually and System.arraycopy the old content first.
Afterwards AbstractStringBuilder.append(char) just has to put the given char in the array whereas AbstractStringBuilder.append(String) has to check a few constraints and calls String.getChars(int, int, char[], int) which does another System.arraycopy of the appended string.
"." is a String consisting of only one character. '.' is a character.
Once you concatenate them together there is no difference.
'' is for character literals.
So you cannot do this:
"Osc" + 'ar' + "Reyes"
Because ar is not a character literal.
In your example it doesn't make much difference because
'/'
is a char literal, and
"/"
is a String literal containing only one character.
Additionally you can use any UTF character with the following syntax
'\u3c00'
So you can also use:
"Osc" + '\u3c00' + "ar
Adding a char is about 25% faster than adding a one character String. Often this doesn't matter however, for example
String s = "hello" + "/" + "world";
This is converted to one String by the compiler so no String concatenation/append will occur at run-time in any case.
Theoretically it is quicker to add a char to a string - Java 6 seems to create StringBuffers under the covers and I remember reading on a Java Performance site that concatenating a char will be marginally quicker.
You will probably find the following articles useful:
Java String Performance Testing
Java String Concatenation
char theLetterA = 'A';
string myString = "a string";
you can only put a single char in between '' if you want to add some more characters use those in between "".
as string is a collection of characters like strong text"hello world"
we can have same thing by using '' like- 'h' 'e' 'l' 'l' 'o' .....
and each has to be stored in different char variable which can be very hectic
so use "" when you have more than one char to store and '' for single char