Convert strings in an array to Title Case - JAVA - java

I have an array of objects (customer) that has components: first_Name & last_Name. I am trying to convert both the first name and last name of each customer to title case. I have tried making several different methods that will convert strings to title case, but all of them have failed. This is the last thing I have tried and I cannot figure out why it would not capitalize the first letter of the first name and the first letter of the last name.
for (Customer c : customers){
c.setFirst_name(c.getFirst_name().charAt(0).toUpperCase());
}
I have checked that the first name and last name indeed contain an only-letter string with a lower case letter as the first letter in each. The error intellisense is giving me is that "char cannot be dereferenced"

This method capitalizes the 1st char of the string and makes the rest lower case:
public static String toTitle(String s) {
return (s.length() > 0) ? s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase() : "";
}
so use it:
for (Customer c : customers){
c.setFirst_name(toTitle(c.getFirst_name()));
c.setLast_name(toTitle(c.getLast_name()));
}

String.charAt() returns a char, which is a primitive type and therefore does not have methods. So the toUpperCase() call is not allowed there.
What you probably want is to create a Character object there, maybe a String. We don't know because you never showed the setFirst_name() signature.

String values is immutable. You try to change the first cahracter. That does not work. You must make a new string: Extract the first character of the original string, convert it to upper case and append the rest of the original string.

Related

Android/Java check car plate number for invalid characters

My question is about checking string for invalid characters, and if they containt replace them.
As example i have string SK5IU0K, which have to divided into to(maybe) two strings. So we have SK5I and U0K.
In this example I would like to check if second part contain "0" and replace it with "O". And in the first part check if it contain I replace it with "1".
I know somehow regex have to be used, but I do not really can imagine currently how to make it work.
This check is for UK car plate numbers which have to followed sertain rule.
https://en.m.wikipedia.org/wiki/Vehicle_registration_plates_of_the_United_Kingdom,_Crown_dependencies_and_overseas_territories
vin = vin.substring(0, 4).replaceAll("I", "1") + vin.substring(4).replaceAll("0", "O");
Checkout String.replace(char oldChar,char newChar)
public static String validateCarPlate(String plate) {
return plate.replace('0', 'O').replace('I', '1');
}

How can I check a string for multiple specific characters in java

I need to check a string to see if it contains any one of these characters (#, $, %, &) in java. I need to check for all 4 at the same time, with out a loop if possible and without regex. I am using this to verify validity of an email address so I cant just check for special characters as the email contains the #. Is there a way to use the .contains method with a switch statement?
Given a String str, and no loops or regular expressions you could presumable call String.contains(CharSequence) with a series of boolean ands like
if (str.contains("#") && str.contains("$") && str.contains("%")
&& str.contains("&")) {
System.out.printf("%s contains #$%%&%n", str);
} else {
System.out.printf("%s does not contain #$%%&%n", str);
}
You should use String.contains(...)
String.subString(String foo) allows you to search for specific case sensitive characters.
Foo.subString(String.ignoreCase("bar") will search foo for the string of characters "bar".
This will return the index of the first letter of "bar", and return -1 if the string is not found.

Getting last few characters from a string

I have a java string containing n number of characters.
How do I extract the LAST few characters from that string?
I found this piece of code online that extracts the first few, but I dont understand it so I cant modify it.
Can anyone help me with this?
String upToNCharacters = s.substring(0, Math.min(s.length(), n));
Try,
String upToNCharacters = s.substring(s.length()-lastCharNumber);
That piece of code does exactly the opposite of what you want. Now let's see why and how we can modify it.
Quick solution
You can modify the code as follows to do what you want:
String lastNchars = s.substring( Math.max(0, s.length()-n));
Explanation
According to the official documentation, Java String class has a special method called substring().
The signature of the method is the following (with overload):
public String substring(int beginIndex, int endIndex))
public String substring(int beginIndex)
The first method accepts 2 parameters as input:
beginIndex: the begin index of the substring, inclusive.
endIndex: the end index of the substring, exclusive.
The second overload will automatically consider as endIndex the length of the string, thus returning "the last part"
Both methods return a new String Object instance according to the input parameters just described.
How do you pick up the right sub-string from a string? The hint is to think at the strings as they are: an array of chars. So, if you have the string Hello world you can logically think of it as:
[H][e][l][l][o][ ][w][o][r][l][d]
[0]...............[6]......[9][10]
If you choose to extract only the string world you can thus call the substring method giving the right "array" indexes (remember the endIndex is exclusive!):
String s = "Hello world";
s.substring(6,11);
In the code snippet you provided, you give a special endIndex:
Math.min(s.length(), n);
That is exactly up to the n th char index taking into account the length of the string (to avoid out of bound conditions).
What we did at the very beginning of this answer was just calling the method and providing it with the beginning index of the substring, taking into account the possible overflow condition if you choose a wrong index.
Please note that any String Object instance can take advantage of this method, take a look at this example, for instance:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);
As you see even "abc", of course, has the substring method!
Have a look at the substring documentation, Basically what it does is, it returns a substring of the string on which it is called, where substring from the index specified by the first parameter and the ends at the second parameter.
So, to get the last few characters, modify the begin index and the end index to the values you need. There is also another version of this method which takes only one parameter, just the begin index, which might be useful for you.
String lastNchars = s.substring(s.length()-n);
One of the String.substring() overloads takes one parameter - the index of the starting index. From that, you can easily implement your function :
String lastFew(String s, int number) {
if (number > s.length()) {
throw new IllegalArgumentException("The string is too short!");
} else return s.substring(s.length()-number);
}

Strings: .replaceAll and .Substring: Practical example explaination?

What steps are actually happening within the following two methods? I have a rough understanding of what the methods are to do, but I do not know how.
Method 1:
public String processDiscardedLetters(String name) {
return name.substring(0, 1)
+ name.substring(1).replaceAll("[aeihouwy]", "");
}
Method 2:
public String processEquivalentLetters(String name) {
name = name.replaceAll("[aeiou]", "a");
name = name.replaceAll("[cgjkqsxyz]", "c");
name = name.replaceAll("[bfpvw]", "b");
name = name.replaceAll("[dt]", "d");
name = name.replaceAll("[mn]", "m");
return name;
}
Example 1:
input: here are my
output: hr r m //replaced with '' (nothing)
Example 2 (first line):
input: cake is king xoxo
output: aaka as kang xoxo // replaced with 'a'
As you can see that the characters inside [] will be replaced with the character you write as 2nd parameter.
Both of the examples use regular expressions to transform input.
The bracket syntax [] is a character class, which means that any character inside it will match with a part of the input.
In particular, doing a string replace with [aeihouwy] will replace all occurrences of any of the letters with the replacement string.
Method 1: Preserves the first letter regardless of what it is, and removes all occurrences of of the of the characters aeihouwy for the rest of the string.
To be more specific, Method 1 is doing the following steps.
Separate the original string into two parts: The first character and the rest of the String. This uses the subString method with arguments 0 and 1 to pull out the first character, and argument 1 to extract the part of the string starting at the second character and ending at end of string.
Use replaceAll to eliminate any of the characters aeihouwy from the second half of the string.
Join the strings together again.
Method 2: For your first example
name = name.replaceAll("[aeiou]", "a"); // Replace of any of the letters `aeiou` with `a` whereever they occur.
String's substring(startIndex, endIndex) methods actually takes a string from a start index (inclusive) to the end index (exclusive) of the string array (A string is a CharSequence which is a "string array"). As you are aware, array counts starts from 0 to N - 1. A substring(startIndex) takes a string starting from index to the end of the string.
The replaceAll(String regularExpression, String replacement) method will replace a string based on the matched regular expression criteria. If a portion of a string matches a regular expression criteria, it gets replaced by a replacement string.
The regular expression in [ and ] are called character classes. These tell the regular expression engine to match only 1 out of those characters. So, if you have [aeihouwy], the words like grey will match since it identified gr[ey] and gr[e]y as well as gre[y]. So, any mentioned words will be replaced with a blank string "".
I hope this helps.

why does this for loop wordcount method not work in java

Can anyone let me know why this wordsearch method doesn't work - the returned value of count is 0 everytime I run it.
public int wordcount(){
String spaceString = " ";
int count = 0;
for(int i = 0; i < this.getString().length(); i++){
if (this.getString().substring(i).equals(spaceString)){
count++;
}
}
return count;
}
The value of getString = my search string.
Much appreciated if anyone can help - I'm sure I'm prob doing something dumb.
Dylan
Read the docs:
The substring begins with the character at the specified index and extends to the end of this string.
Your if condition is only true once, if the last character of the string is a space. Perhaps you wanted charAt? (And even this won't properly handle double spaces; splitting on whitespace might be a better option.)
Because substring with only one argument returns the sub string starting from that index till the end of the string. So you're not comparing just one character.
Instead of substring define spaceString as a char, and use charAt(i)
this.getString().substring(i) -> this returns a sub string from the index i to the end of the String
So for example if your string was Test the above would return Test, est, st and finally t
For what you're trying to do there are alternative methods, but you could simple replace
this.getString().substring(i)
with
spaceString.equals(this.getString().charAt(i))
An alternative way of doing what you're trying to do is:
this.getString().split(spaceString)
This would return an array of Strings - the original string broken up by spaces.
Read the documentation of the method you are using:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)
I.e. the count will be non zero only if you have a space on the end of your string
Using substring as you are will not work. If the value of getString() is "my search string" every iteration through the loop with have substring(i) return:
my search string
y search string
search string
search string
earch string
arch string
rch string
ch string
h string
string
string
tring
ring
ing
ng
g
Notice none of those equals " ".
Try using split.
public int countWords(String s){
return s.split("\\s+").length;
}
Change
if (this.getString().substring(i).equals(spaceString))
to
if (this.getString().charAt(i) == ' ')
this.getString().substring(i) returns a string from the index of (i) to the end of the string.
Example: for i=5, it will return "rown cow" from the string "the brown cow". This functionality isn't what you need.
If you pepper System.out.println() throughout your code (or use the debugger), you will see this.
I think it would be better to use something like String.split() or charAt(i).
By the way, even if you fix your code by counting spaces, it will not return the correct value for these conditions: "my dog" (word count=2) and "cow" (word count=1). There is also a problem if there are more than one space between words. ALso, this will produce a word cound of three:
" the cow ".

Categories

Resources