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);
Related
ie. My string is "pqrstuw". How can I get " t" with its postion 4. I want to edit each character and change its postion. Is it possible in Java?
You can use a for loop and call String#charAt()... this is the character at the zero base-index, always having in mind that Strings objects are inmutable.
Assuming a string variable 'word' contains what you need. Use the code below to print the various characters in it. Also add the headerfile needed ( java.lang.String; )
int size = word.length(); // Get length of string
for(int i =0 ; i<size ; i++) {
System.out.println(word.charAt(i)); // To print i+1'th letter
}
string_name.charAt(i) will give you the 'i+1'th character in your string. In your case, if word = "pqrstuvw", then word.charAt(3) will give you 't' which is the 4th character of the string.As for your second question, you need to be a little more clear on what kind of position changing you want to do in your question.
The following is an answer from another similar question: "Replacing a character at a specific position in the string.
Strings are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
All we know that String is a Immutable (final) class defined in JDK. So, It is not recommend and very cozy to manipulate a String in Java.
There are two simple ways to manipulate the string in Java.
Using StringBuilder Class.
Change to char Array Using .charArray() method of String Class .
Using StringBuilder Class
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type.
Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder.
The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
Now Here is the code
String str = "pqrstuw";
StringBuilder strBuild = new StringBuilder(str);
strBuild.indexOf("t"); //return first index where t is found which is 4.
strBuild.lastIndexOf("t"); //return last index where t is found which is 4.
strBuild.getCharAt(4); // you will get t.
strBuild.setCharAt(4,'v');
strBuild.append("v"); append element at last.
there are various more overloaded method there is StringBuilder Class. You can do it in Your Way of Manipulation.
Using char Array
String str = "pqrstuw";
char [] arr_str = str.toCharArray(); //it convert your String into a char Array.
//after manipulation you can change your char Array to String as like
str = arr_str.toString();
I would like to find same word in two string.
startpoint = newresult.indexOf('\'');
endpoint = newresult.lastIndexOf('\'');
variables = newresult.substring(startpoint, endpoint);
variables = variables.replace("\r\n", ",");
variables = variables.replaceAll("'", "");`
String variables:
cons,john,$,alex,manag;
String second:
ins_manages(john,cons)
As it is seen, both strings they have john and cons and I want to check if both have same char sequences or not but I don't know how it can be checked? Is there any way to check it directly?
Solution:
String [] newvar;
newvar = variables.split(",");
After that, I used a for loop and matched them one by one.
BR
Split both the strings and compare the individual words using foreach as shown below:
String first = "hello world today";
String second = "Yet another hello worldly day today";
//split the second string into words
List<String> wordsOfSecond = Arrays.asList(second.split(" "));
//split and compare each word of the first string
for (String word : first.split(" ")) {
if(wordsOfSecond.contains(word))
System.out.println(word);
}
Your requirements are a little ambiguous. You're asking to find the same singular word in two strings, then your sample asks for finding two words in the same strings.
For verifying that one single word is in two strings, you can just do:
public boolean bothStringsContainWord(String s1, String s2, String word) {
return s1.contains(word) && s2.contians(word);
}
You can put that in a loop if you need to do it over multiple words. Again, your requirements are a little fuzzy though; if you straighten them up a more efficient solution probably exists.
Say I have two randomly generated Strings.
What can I do to make a single String with the two Strings generated, while being able to split them to get the original two Strings for later use?
For example, I have "[aweiroj\3aoierjvg0_3409" and " 4093 w_/e9 ". How can I attach those two words into one variable while being able to split them to original two Strings?
My problem is, I can't seem to find a regex for .spit() because those two strings can have any chararacters(alpabet, integer, \, /, spaces...).
EDIT
I just thought of a real life case where this could be used. Sometimes, sending plain text over network(HTTP) is better than xml or json. Slow server with fast broadband - use xml or json, fast server with slow broadband - use plain text. The answers below could prevent plain text injection. However, these methods are not benchmarked or tested, I would probably test these methods before actually using them.
The short answer is: Don't do that. Use an array, or a class with two data members, but combining the strings together into one string is probably a bad idea.
But if you have some truly obscure use case, you can:
Create a sufficiently-unique delimiter, like "<<Jee Seok Yoon's Delimiter>>".
final static String DELIM = "<<Jee Seok Yoon's Unique Delimiter>>";
String a = /*...*/;
String b = /*...*/;
String combined = a + DELIM + b;
int breakAt = combined.indexOf(DELIM);
String a1 = combined.substring(0, breakAt);
String b1 = combined.substring(breakAt + DELIM.length());
Have a simpler delimiter that you escape if present in the string.
Remember the length of the first string and store it in your unified string followed by an "end of length" delimiter.
String a = /*...*/;
String b = /*...*/;
String combined = String.valueOf(a.length()) + "|" + a + b;
int breakAt = combined.indexOf("|");
int len = Integer.parseInt(combined.substring(0, breakAt), 10);
String a1 = combined.substring(breakAt + 1, len);
String b1 = combined.substring(breakAt + 1 + len);
(Both code examples are completely off-the-cuff and untested.)
I would create a Class that holds both Strings and is able to print them seperatly and combined.
This one simply extends ArrayList so you don't need to reimplement add, get and so on:
public class ConcatedString extends ArrayList<String>
{
public String concated() {
StringBuilder b = new StringBuilder();
for (String string : this)
{
b.append(string);
}
return b.toString();
}
}
If this is a matter of serialization of some (obscure) kind, then there is at least one obvious way to do this.
Encode the strings using some encoding (HTML encoding is an easy and readable choice). Pick a character that the encoded strings cannot possibly contain, use that as a separator and concatenate them all.
Then, to retrieve, separate the strings by that character and decode the substrings using your initial method in reverse.
If you want it to work in every cases, you need to define 2 special characters :
A delimiter character
An escape character.
1-Encoding : When you concat the 2 String :
In both String,
replace all characters which equal the escape character with 2 escape characters
replace all characters which equal the delimiter character with escape + delimiter
then concat both String with the delimiter character between them.
2-Decoding : When you decode the String :
If the current character is a escape character while the next one is also a escape character, replace it with only one escape character and skip 1 character.
If the current character is a escape character while the next one is also a delimiter character, replace it with only one delimiter character and skip 1 character.
If the current character is the delimiter character, then you are between the 2 original Strings.
Here is a working example :
//I make on purpose a bad choice for escape/delimiter characters
private static final char DELIMITER = '1';
private static final char ESCAPE = '2';
public static String encode(String s1, String s2){
StringBuilder sb = new StringBuilder();
subEncode(s1, sb);
sb.append(DELIMITER);
subEncode(s2, sb);
return sb.toString();
}
private static void subEncode(String s, StringBuilder sb) {
for(char c : s.toCharArray()) {
if(c == ESCAPE) {
sb.append(ESCAPE);
sb.append(ESCAPE);
}else if(c == DELIMITER) {
sb.append(ESCAPE);
sb.append(DELIMITER);
}else {
sb.append(c);
}
}
}
public static String[] decode(String encoded) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
StringBuilder currentSb = sb1;
char[] chars = encoded.toCharArray();
for(int i = 0; i< chars.length ; i++) {
if(chars[i] == ESCAPE) {
if(chars.length < i+2) {
throw new IllegalArgumentException("Malformed encoded String");
}
if(chars[i+1] == ESCAPE) {
currentSb.append(ESCAPE);
}else if(chars[i+1] == DELIMITER) {
currentSb.append(DELIMITER);
}
i++;
}else if(chars[i] == DELIMITER) {
currentSb=sb2;
}else {
currentSb.append(chars[i]);
}
}
return new String[]{sb1.toString(), sb2.toString()};
}
Test :
public static void main(String[] args) {
//Nominal case :
{
String s1 = "aaa";
String s2 = "bbb";
System.out.println("Encoded : " + encode(s1, s2));
System.out.println("Decoded" + Arrays.asList(decode(encode(s1,s2))));
}
//with bad characters :
{
String s1 = "111";
String s2 = "222";
System.out.println("Encoded : " + encode(s1, s2));
System.out.println("Decoded" + Arrays.asList(decode(encode(s1,s2))));
}
//with random characters :
{
String s1 = "a11a1";
String s2 = "1112bb22";
System.out.println("Encoded : " + encode(s1, s2));
System.out.println("Decoded" + Arrays.asList(decode(encode(s1,s2))));
}
}
Output :
Encoded : aaa1bbb
Decoded[aaa, bbb]
Encoded : 2121211222222
Decoded[111, 222]
Encoded : a2121a21121212122bb2222
Decoded[a11a1, 1112bb22]
Another way to do this, format the encoded String using the following format :
size_of_str_1:str1|size_of_str2:str2
Example : if string1 is 'aa' and string2 is 'bbbb', the encoded String is : '2:aa|4:bbbb'.
You decode it via String#subString(). the "hard" part is to parse the string until you finished to read the size of the next String.
Trying to write a short method so that I can parse a string and extract the first word. I have been looking for the best way to do this.
I assume I would use str.split(","), however I would like to grab just the first first word from a string, and save that in one variable, and and put the rest of the tokens in another variable.
Is there a concise way of doing this?
The second parameter of the split method is optional, and if specified will split the target string only N times.
For example:
String mystring = "the quick brown fox";
String arr[] = mystring.split(" ", 2);
String firstWord = arr[0]; //the
String theRest = arr[1]; //quick brown fox
Alternatively you could use the substring method of String.
You should be doing this
String input = "hello world, this is a line of text";
int i = input.indexOf(' ');
String word = input.substring(0, i);
String rest = input.substring(i);
The above is the fastest way of doing this task.
To simplify the above:
text.substring(0, text.indexOf(' '));
Here is a ready function:
private String getFirstWord(String text) {
int index = text.indexOf(' ');
if (index > -1) { // Check if there is more than one word.
return text.substring(0, index).trim(); // Extract first word.
} else {
return text; // Text is the first word itself.
}
}
The simple one I used to do is
str.contains(" ") ? str.split(" ")[0] : str
Where str is your string or text bla bla :). So, if
str is having empty value it returns as it is.
str is having one word, it returns as it is.
str is multiple words, it extract the first word and return.
Hope this is helpful.
import org.apache.commons.lang3.StringUtils;
...
StringUtils.substringBefore("Grigory Kislin", " ")
You can use String.split with a limit of 2.
String s = "Hello World, I'm the rest.";
String[] result = s.split(" ", 2);
String first = result[0];
String rest = result[1];
System.out.println("First: " + first);
System.out.println("Rest: " + rest);
// prints =>
// First: Hello
// Rest: World, I'm the rest.
API docs for: split
for those who are searching for kotlin
var delimiter = " "
var mFullname = "Mahendra Rajdhami"
var greetingName = mFullname.substringBefore(delimiter)
like this:
final String str = "This is a long sentence";
final String[] arr = str.split(" ", 2);
System.out.println(Arrays.toString(arr));
arr[0] is the first word, arr[1] is the rest
You could use a Scanner
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
The scanner can also use delimiters
other than whitespace. This example
reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
None of these answers appears to define what the OP might mean by a "word". As others have already said, a "word boundary" may be a comma, and certainly can't be counted on to be a space, or even "white space" (i.e. also tabs, newlines, etc.)
At the simplest, I'd say the word has to consist of any Unicode letters, and any digits. Even this may not be right: a String may not qualify as a word if it contains numbers, or starts with a number. Furthermore, what about hyphens, or apostrophes, of which there are presumably several variants in the whole of Unicode? All sorts of discussions of this kind and many others will apply not just to English but to all other languages, including non-human language, scientific notation, etc. It's a big topic.
But a start might be this (NB written in Groovy):
String givenString = "one two9 thr0ee four"
// String givenString = "oňňÜÐæne;:tŵo9===tĥr0eè? four!"
// String givenString = "mouse"
// String givenString = "&&^^^%"
String[] substrings = givenString.split( '[^\\p{L}^\\d]+' )
println "substrings |$substrings|"
println "first word |${substrings[0]}|"
This works OK for the first, second and third givenStrings. For "&&^^^%" it says that the first "word" is a zero-length string, and the second is "^^^". Actually a leading zero-length token is String.split's way of saying "your given String starts not with a token but a delimiter".
NB in regex \p{L} means "any Unicode letter". The parameter of String.split is of course what defines the "delimiter pattern"... i.e. a clump of characters which separates tokens.
NB2 Performance issues are irrelevant for a discussion like this, and almost certainly for all contexts.
NB3 My first port of call was Apache Commons' StringUtils package. They are likely to have the most effective and best engineered solutions for this sort of thing. But nothing jumped out... https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html ... although something of use may be lurking there.
You could also use http://download.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html
I know this question has been answered already, but I have another solution (For those still searching for answers) which can fit on one line:
It uses the split functionality but only gives you the 1st entity.
String test = "123_456";
String value = test.split("_")[0];
System.out.println(value);
The output will show:
123
The easiest way I found is this:
void main()
String input = "hello world, this is a line of text";
print(input.split(" ").first);
}
Output: hello
Assuming Delimiter is a blank space here:
Before Java 8:
private String getFirstWord(String sentence){
String delimiter = " "; //Blank space is delimiter here
String[] words = sentence.split(delimiter);
return words[0];
}
After Java 8:
private String getFirstWord(String sentence){
String delimiter = " "; //Blank space is delimiter here
String firstWord = Arrays.stream(sentence.split(delimiter))
.findFirst()
.orElse("No word found");
}
String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);
You can also do like these
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);