My code doesnt convert ex. dog_cat_dog into dogCatDog. The out put of my code is dogCat_dog. Trying to make a loop that doesn't stop at the first "_":
public String underscoreToCamel(String textToConvert) {
int index_= textToConvert.indexOf("_",0);
String camelCase="";
String upperCase = "";
String lowerCase="";
for (int i=0; i < textToConvert.length(); i++){
if(i==index_){
upperCase= (textToConvert.charAt(index_+1)+upperCase).toUpperCase();
upperCase= upperCase+ textToConvert.substring(index_+2);
}
else{
lowerCase=textToConvert.substring(0,index_);
}
camelCase=lowerCase+upperCase;
}
return camelCase;
}
I would do the following: make the method static, it does not use any class state. Then instantiate a StringBuilder with the passed in value, because that is mutable. Then iterate the StringBuilder. If the current character is underscore, delete the current character, then replace the now current character with its upper case equivalent. Like,
public static String underscoreToCamel(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '_') {
sb.deleteCharAt(i);
char ch = Character.toUpperCase(sb.charAt(i));
sb.setCharAt(i, ch);
}
}
return sb.toString();
}
I tested like
public static void main(String[] args) {
System.out.println(underscoreToCamel("dog_cat_dog"));
}
Which outputs (as requested)
dogCatDog
You can split on '_' then rebuild.
public static String underscoreToCamel(String textToConvert) {
String [] words = textToConvert.split("_");
StringBuilder sb = new StringBuilder(words[0]);
for (int i = 1; i < words.length; i++) {
sb.append(Character.toUpperCase(words[i].charAt(0)));
sb.append(words[i].substring(1));
}
return sb.toString();
}
I think an easy way to solve this is to first consider the base cases, then tackle the other cases
public static String underscoreToCamel(String textToConvert){
//Initialize the return value
String toReturn = "";
if (textToConvert == null){
//Base Case 1: null value, so just return an empty string
return "";
} else if (textToConvert.indexOf("_") == -1) {
//Base Case 2: string without underscore, so just return that string
return textToConvert;
} else {
//Primary Case:
//Find index of underscore
int underscore = textToConvert.indexOf("_");
//Append everything before the underscore to the return string
toReturn += textToConvert.substring(0, underscore);
//Append the uppercase of the first letter after the underscore
toReturn += textToConvert.substring(underscore+1, underscore+2).toUpperCase();
//Append the rest of the textToConvert, passing it recursively to this function
toReturn += underscoreToCamel(textToConvert.substring(underscore+2));
}
//Final return value
return toReturn;
}
Related
I am trying to implement a function that searches a given string and reverses capitalization of all occurrences of particular alphabetical characters (case insensitive), leaving numbers, special characters, and other alphabetical characters unaffected.
For example, if theString = "abc123XYZ" and reverseCaps= "cyz", the result should be "abC123Xyz".
I have tried various implementations and fixes, but cannot get it to work properly. The result I am getting now is "ABC123xyz".
Here is my code:
public static String flipCaseChars(String theString, String reverseCap) {
StringBuilder buf = new StringBuilder(theString.length());
for (int i = 0; i < theString.length(); i++) {
char c = theString.charAt(i);
if (Character.isUpperCase(c)) {
buf.append(Character.toLowerCase(c));
}
else if (Character.isLowerCase(c)) {
buf.append(Character.toUpperCase(c));
}
// if char is neither upper nor lower
else {
buf.append(c);
}
}
return buf.toString();
}
What should I do? Any help would be very much appreciated.
public static String flipCaseChars(String theString, String reverseCap) {
StringBuilder buf = new StringBuilder(theString.length());
for (int i = 0; i < theString.length(); i++) {
char c = theString.charAt(i);
if (reverseCap.indexOf(c) >= 0){
if (Character.isUpperCase(c)) {
buf.append(Character.toLowerCase(c));
} else if (Character.isLowerCase(c)) {
buf.append(Character.toUpperCase(c));
} else {
buf.append(c);
}
} else {
buf.append(c);
}
}
return buf.toString();
}
Am I missing something here? I see that some answers here are getting voted up but they're not doing what the OP has requested. According to the example input ("abc123XYZ") and output ("abC123Xyz"), I see it that the letter-case of the characters within the reverseCaps string variable is irrelevant. They could have been any letter-case but, if any one of them are encountered within the input string (theString) regardless of current letter-case state any one of the supplied characters letter-case if flipped to its' opposing state.
So if the Input String was: ab-c-123-C-XYz and the reverseCaps variable contained "cyz" then the output should be: ab-C-123-c-XyZ. Am I mistaken?
If I'm not mistaken then the following code will carry out the task explained above:
public static String flipCaseCharacters(String inputString, String charactersToFlip) {
StringBuilder newString = new StringBuilder();
for (char inChar : inputString.toCharArray()) {
for (char ctFlip : charactersToFlip.toCharArray()) {
if (Character.toUpperCase(inChar) == Character.toUpperCase(ctFlip)) {
inChar = Character.isUpperCase(inChar) ?
Character.toLowerCase(inChar) :
Character.toUpperCase(inChar);
break;
}
}
newString.append(inChar);
}
return newString.toString();
}
An easier way is to loop through the reverseCap String and do a conditional replace
for (char c : reverseCap.toCharArray()) {
if (Character.isLowerCase(c)) {
theString = theString.replace(c, Character.toUpperCase(c));
}
else {
theString = theString.replace(c, Character.toLowerCase(c));
}
}
return theString;
No need to check if the character is upper or lower case. It just flips case of the character as appropriate. This presumes that the reverse list of characters is all lowercase, as shown in the example.
It works by checking and then manipulating the bit 0x20that determines upper and lower case in ASCII characters.
The ^ is the exclusive OR operator that flips to the opposite case by flipping the case bit.
public static String flipCaseChars(String theString, String reverseCap) {
StringBuilder sb = new StringBuilder();
for (char c : theString.toCharArray()) {
// is the character in the list?
if (reverseCap.indexOf(c | 0x20) >= 0) {
c ^= 0x20; // flip the case
}
sb.append(c);
}
return sb.toString();
}
I basically made a HashSet<Character> of reverseCap and then the rest follows #toootooo's answer
Here it is:
static String flipCaseChars(String theString, String reverseCap) {
final StringBuilder stringBuilder = new StringBuilder(theString.length());
HashSet<Character> collect = new HashSet<>();
for (int i = 0; i < reverseCap.length(); i++) {
collect.add(Character.toLowerCase(reverseCap.charAt(i)));
collect.add(Character.toUpperCase(reverseCap.charAt(i)));
}
for (int i = 0; i < theString.length(); i++) {
char currentChar = theString.charAt(i);
if (collect.contains(currentChar)) {
if (Character.isUpperCase(currentChar)) {
currentChar = Character.toLowerCase(currentChar);
} else if (Character.isLowerCase(currentChar)){
currentChar = Character.toUpperCase(currentChar);
}
}
stringBuilder.append(currentChar);
}
return stringBuilder.toString();
}
The only advantage of this approach is that the lookup of the characters in reverseCap is done in constant time and the time complexity is directly propertional to the length of theString.
for a school assignment, I have to cut the string off at a certain character. It takes an email as input, ex: name#mail.ca, and it has to print everything before the # sign. We are not allowed to use substring, index or split. I've attached what i've tried so far.
public static void main(String[] args) {
getPrefix("name#email.ca");
}
public static String getPrefix(String email) {
String prefix = "";
for (int i = 0; i < email.length(); i++) {
if (email.charAt(i) == '#') {
break;
}
prefix += email.charAt(i);
}
return prefix;
}
if i set the input as name#email.ca it prints: ame#email.caame#email.caame#email.caame#email.ca
So right now it is only taking away the first character, when instead I need it to take away everything from the # onwards.
Also,I have to return the value rather than just print it, so how would I do that outside the loop.
Use StringBuilder to append each char of string before #, If you can't use StringBuilder you can use String but i won't recommended to use string for this
public static String getPrefix(String email) {
StringBuilder builder = new StringBuilder(); // or String str = "";
for (int i = 0; i < email.length(); i++) {
if (email.charAt(i) == '#') {
break;
}
builder.append(email.charAt(i)); //or str+=email.charAt(i);
}
return builder.toString(); //or return str;
}
I'm having a problem getting the unique letters and digits out of an array of strings, and then returning them. I am having a formatting issue.
The given input is: ([abc, 123, efg]) and is supposed to return abcefg123,
however, mine returns: abc123efg
how can I fix this since arrays.sort() will end up putting the numbers first and not last?
Here is my method so far:
public static String getUniqueCharsAndDigits(String[] arr) {
String str = String.join(",", arr);
String myString = "";
myString = str.replaceAll("[^a-zA-Z0-9]", "");
for(int i = 0; i < str.length(); i++) {
if(Character.isLetterOrDigit((i))){
if(myString.indexOf(str.charAt(i)) == -1) {
myString = myString + str.charAt(i);
}
}
}
return myString;
}
What you want to do is create two strings, one with the letters, one with the digits.
public static String getUniqueCharsAndDigits(String[] arr) {
String str = String.join("", arr);
String myLetters, myDigits;
myLetters = myDigits = "";
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(Character.isLetter(c)){
if(myLetters.indexOf(c) == -1) {
myLetters += c;
}
} else if(Character.isDigit(c)){
if(myDigits.indexOf(c) == -1) {
myDigits += c;
}
}
}
//if they need to be sorted, sort each one individually here
return myLetters + myDigits;
}
I've modified your code and deleted the unnecessary parts of it.
public static String filterPhoneNumber(String phoneNumber) {
Character[] characters = new Character[phoneNumber.length()];
if (characters.length > 9)
{
for (int i = 0; i < characters.length; i++)
{
if (characters[i] != ' ')
{
characters[i] = phoneNumber.charAt(i);
} else
{
Log.d("asd", "wrroooonggggggggg");
}
}
}
return phoneNumber;
}
Im trying to filter empty chars in the number, but when 2 or more empty chars are found in the string, it removes only the first.
Your problem is that you increase i in the for-loop and when you find a space you skip it. When you in the next loop set the number in characters you have skipped one entry. You must use two stepping variables, one for stepping phoneNumber and one for characters.
It looks like you want to return a filter phone number, but are returning the values that you sent in.
There is a search and replace method on String that you can use.
public static String filterPhoneNumber(String phoneNumber) {
return phoneNumber.replaceAll(" ","");
}
Here is how it is used: http://runnable.com/VUfHvPvHoEdLO3id/filterphonenumber-for-java
If you use
char[] characters = new char[phoneNumber.length()];
it works.
your characters array should be of the type char[]
characters array is never initialized, so characters[i] != ' ' is always true (provided that you fix the array type, else should throw a NullPointerException)
you're assign characters[i] = phoneNumber.charAt(i) but you never read it afterwards.
If your goal is to remove spaces just do this:
public static String filterPhoneNumber(String phoneNumber) {
return phoneNumber.replaceAll(" ", "");
}
Working 100%
public static String filterPhoneNumber(String phoneNumber) {
byte[] number = phoneNumber.getBytes();
byte[] array = new byte[phoneNumber.length()];
int count=0;
for (int i = 0; i < number.length; i++){
if (number[i] != ' '){
array[count++] = number[i];
}
}
return new String(array);
}
public static void main(String[] args) {
String res = filterPhoneNumber(" +28 23");
System.out.println(res); //OUTPUT "+2823"
}
I am working on a program that is a word guessing game, and the list of words is used from an array list. I am working through a method where the user will input a character to guess if it is in the word. After that, the program tells the user the character appears in "x" number of positions in the word (that is displayed to the user as *****). I want to now replace the "*****" with the character at the given position. I know that the program has to scan through the word and where that character is, it will replace the "*" with the character. How do I do that? So far, this is all that I have for this method...
private static String modifyGuess(char inChar, String word,String currentGuess){
int i = 0;
String str = " ";
while (i < word.length()){
if(inChar == word.charAt(i)){
}
else{
i++;
}
}
return
}
private static String modifyGuess(char inChar, String word, String currentGuess) {
int i = 0;
// I assume word is the original word; currentGuess is "********"
StringBuilder sb = new StringBuilder(currentGuess);
while (i < word.length()) {
if (inChar == word.charAt(i)) {
sb.setCharAt(i, inChar);
}
i++; // you should not put this line in the else part; otherwise it is an infinite loop
}
return sb.toString();
}
You can use this:
public String replace(String str, int index, char replace){
if(str==null){
return str;
}else if(index<0 || index>=str.length()){
return str;
}
char[] chars = str.toCharArray();
chars[index] = replace;
return String.valueOf(chars);
}
Or you can use the StringBuilder Method:
public static void replaceAll(StringBuilder builder, String from, String to)
{
int index = builder.indexOf(from);
while (index != -1)
{
builder.replace(index, index + from.length(), to);
index += to.length(); // Move to the end of the replacement
index = builder.indexOf(from, index);
}
}