Hey I'm having another problem with my coding assignment tonight. I'm supposed to write a method to add "bool" in front of every "a" in the passed string s. But my code only adds it to one specific "a". How would a go about fixing this with a while loop. Thanks!
Lets say s=banana
public static String insertBool(String s){
int pos=s.indexOf("a");
if(pos>-1){
String firstS=(s.substring(0,pos));
String secondS=(s.substring(pos, s.length()));
return(firstS+"bool"+secondS);
}
else
return s;
}
You could just replace all the a's in the string with "boola".
public static String insertBool(String s) {
return s.replaceAll("a", "boola");
}
You could use String.replace()
public static String insertBool(String s) {
if (s == null) {
return null;
}
return s.replace("a", "boola");
}
Or you could use a more complicated while and something like,
public static String insertBool(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
int i = 0;
char[] arr = s.toCharArray();
while (i < arr.length) {
if (arr[i] == 'a') {
sb.append("bool");
}
sb.append(arr[i]);
i++;
}
return sb.toString();
}
Related
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;
}
I was wondering what is exactly wrong with the following code. I'm getting error on the line after the if statement. This code takes a string with both uppercase and lowercase letters but returns the string after converting the uppercase letters to lowercase.
public class Main {
public static void main(String[] args) {
toLowerCase("HeLloWoRlD!");
}
private static String toLowerCase(String str) {
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
str.charAt(i) = Character.toLowerCase(str.charAt(i));
}
}
return str;
}
}
str.charAt(i) cannot be the left hand side of an assignment operator. It's a value returned by a method call, you can't assign to it.
Besides, Strings are immutable. You cannot modify the characters of str.
You'll have to create a new String for your method to return.
For example:
private static String toLowerCase(String str) {
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
sb.append (Character.toLowerCase(str.charAt(i)));
} else {
sb.append (str.charAt(i));
}
}
return sb.toString();
}
Change you code to the following :
private static String toLowerCase(String str) {
StringBuffer lower = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
lower.append(Character.toLowerCase(str.charAt(i)));
} else {
lower.append(str.charAt(i));
}
}
return lower.toString();
}
public static void main(String[] args) throws IOException {
System.out.println(toLowerCase("HeLloWoRlD!"));
}
A string is immutable so you can't change the existing one on the fly. Instead you can create a StringBuffer and append the values accordingly as you iterate over the original str.
String is immutable so you cannot change (reassign) the characters inside the string.
Here is the simplest solution, just using the built in method in String class:
private static String toLowerCase(String str) {
return str == null ? null : str.toLowerCase(); //consider str.toLowerCase(Locale.ROOT) if you are using non english language with special characters
}
You are making use of the String.charAt(i) which returns character Value at that position. It is not the reference location that you can assign a value to.
Please check the below documentation.
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#charAt-int-
You need to convert to a character Array the string if you want to modify it using the charAt feature
private static String toLowerCase(String str) {
char[] newStr = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
newStr[i] = Character.toLowerCase(str.charAt(i));
}
}
return new String(newStr);
}
The method charAt(i) is used for getting character by index(position) in the string. However, You used it for setting, what is not right.
So, in your case, method toLowerCase() should return new String object, for example.
private static String toLowerCase(String str) {
String returning_Str = "";
for (int i = 0; i < str.length(); i++) {
char test_char = str.charAt(i);
if (Character.isUpperCase(test_char)) {
test_char = Character.toLowerCase(test_char);
}
returning_Str += test_char;
}
return returning_Str;
}
You cannot change the content of a String. You have to create a new object instead:
public class Main {
public static void main(String[] args) {
toLowerCase("HeLloWoRlD!");
}
private static String toLowerCase(String str) {
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
str = new String(str.replace(str.charAt(i),Character.toLowerCase(str.charAt(i))));
}
}
return str;
}
}
First take a variable the assign value on it.
This code will work as expected
public class Main {
public static void main(String[] args) {
System.out.println(toLowerCase("HeLloWoRlD!"));
}
private static StringBuffer toLowerCase(String str) {
StringBuffer buf=new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c=str.charAt(i);
if (Character.isUpperCase(str.charAt(i))) {
c = Character.toLowerCase(str.charAt(i));
buf.append(c);
}else{
buf.append(c);
}
}
return buf;
}
}
private static String toLowerCase(String str){
return str.chars().map(Character::toLowerCase).collect(StringBuilder::new,
StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
or
private static String toLowerCase(String str){
return str.toLowerCase();
}
I tried to recursively reverse a string in Java, but I am getting just the last character as output.
I looked up online and most of the codes have modified the input string. I am trying to build the output from empty string to reversed string. Please tell me what is wrong in my program.
class reverseStringRecursion
{
public static void main(String args[])
{
System.out.println(reverse());
}
public static String reverse()
{
String strInput = " Hello I am my name.";
String output = "";
return recursiveHelper(strInput, 0, output);
}
public static String recursiveHelper(String strInput, int index, String output)
{
if(index == (strInput.length() - 1 ))
output += strInput.charAt(index) + "";
else
output+= recursiveHelper(strInput, index + 1, output) +"";
return output;
}
}
The above code is returning output '.' only and nothing else. PLease help.
Others have done a good job of explaining why your code doesn't work. For comparison, here's a working version with some comments:
public static void main(String args[])
{
System.out.println(reverse("Hello I am my name."));
}
public static String reverse(String text)
{
// Base case:
// If the string is empty, we're done.
if (text.length() == 0) {
return "";
} else {
// reverse("hello") = reverse("ello") + "h"
return reverse(text.substring(1)) + text.charAt(0);
}
}
Since String in Java are immuatable, passing it by parameter is useless on this case, so I removed it.
public class Main {
public static void main(String args[]) {
System.out.println(reverse());
}
public static String reverse() {
String strInput = " Hello I am my name.";
return recursiveHelper(strInput, 0);
}
public static String recursiveHelper(String strInput, int index) {
String output;
if(index == (strInput.length() - 1 )){
output = strInput.charAt(index) + "";
}else{
output = recursiveHelper(strInput, index + 1) + strInput.charAt(index);
}
return output;
}
}
Try it online!
Since strInput always contains the original String, the following condition makes sure your code only takes the last character of that String and ignore all the other characters:
if(index == (strInput.length() - 1 ))
output += strInput.charAt(index) + "";
To build the reversed String recursively, you have to append the last character of the String to the reverse of the sub-string of the first length()-1 characters.
This means that you don't need the 2nd and 3rd arguments of your method, and strInput should be passed a shorter String in each recursive call.
public static String reverse (String strInput)
{
if(strInput.length() <= 1)
return strInput;
else
return strInput.charAt(strInput.length()-1) + reverse (strInput.substring(0,strInput.length()-1));
}
I would change your function recursiveHelper() to only receive one argument (the String that you want to reverse). Using the substring method from Java you can do it like this:
public static String recursiveHelper(String strInput) {
if(strInput.length() == 1) {
return strInput;
}
else if(strInput == "") {
return "";
}
String subString1 = recursiveHelper(strInput.substring(0, strInput.length()/2)); // Here we copy the first half of the String to another String
String subString2 = recursiveHelper(strInput.substring(strInput.length()/2)); // Here we do the same, but with the second half of the original String
return susbString2 + subString1; // It is very important that you sum the two substrings in this order!
}
Modified your class:
public class ReverseStringRecursion {
public static void main(String args[])
{
System.out.println(reverse());
}
public static String reverse()
{
String strInput = "My Name is Jane Doe";
String output = "";
return recursiveHelper(strInput,0);
}
public static String recursiveHelper(String strInput, int index)
{
if(index == (strInput.length() - 1 ))
return "" + strInput.charAt(index) ;
else
return recursiveHelper(strInput,index+1) + strInput.charAt(index);
}
}
public class Main
{
public static void main(String[] args) {
String str1="abc";
String str2="";
for(int i=str1.length()-1;i>=0;i--)
{
str2=str2+Character.toString(str1.charAt(i));
}
System.out.println("After Reverse: "+str2);
}
}
1) Base case
if left>=right - do nothing
2) otherwise swap s[left] and s[right} and call helper(left+1, right-1)].
class Solution {
public void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while (left < right) {
char tmp = s[left];
s[left++] = s[right];
s[right--] = tmp;
}
}
}
I need to create a program that recursively parses a string into smaller substrings. Every substring is one letter shorter than the previous; once it's at the end it would redisplay the word, but with the first letter sliced off, and then substrings of that.
For example: Given the word 'Slugger' the program would display
Slugger
Slugge
Slugg
Slug
Slu
Sl
S
lugger
lugge
lugg
lug
lu
l
And on and on.
This is part of my code so far that is supposed to break things up:
private static void stringParser(String str)
{
if(str.length() < 1)
{
return;
}
else if(str.length() == 0)
{
removeFirstChar(str, 1);
}
else
{
System.out.println(str);
stringParser(str.substring(0, str.length() - 1));
}
} // End stringParser method
private static void removeFirstChar(String str, int i)
{
String strNew = str.substring(i);
stringParser(strNew);
return strNew;
} // End removeFirstChar method
I think I've got all the pieces and parts that I need, but perhaps just don't have them in the right order to do what I want.
Any help is greatly appreciated.
Thank you!
I have added the following in your code. See if this works
public static void main(String[] args) {
String str = "slugger";
for(int i=0;i<str.length();i++) {
stringParser(str.substring(i));
}
}
Complete code.....
public class Test {
public static void main(String[] args) {
String str = "slugger";
for(int i=0;i<str.length();i++) {
stringParser(str.substring(i));
}
}
private static void stringParser(String str)
{
if(str.length() < 1)
{
return;
}
else if(str.length() == 0)
{
removeFirstChar(str, 1);
}
else
{
System.out.println(str);
stringParser(str.substring(0, str.length() - 1));
}
} // End stringParser method
private static void removeFirstChar(String str, int i)
{
String strNew = str.substring(i);
stringParser(strNew);
str = strNew;
}
}
I have the following problem.
The recursive method public static String doSomeMagic("Test") should return:
TTeesstt
TTeess
TTee
TT
I've implemented this behaviour already like this:
public static String rowFunction(String s) {
String toReturn = new String();
if (!s.isEmpty()) {
toReturn = String.valueOf(s.charAt(0));
toReturn += toReturn + rowFunction(s.substring(1));
}
return toReturn;
}
public static String doSomeMagic(String s) {
String toReturn = new String();
if (!s.isEmpty()) {
toReturn = rowFunction(s) + "\n" + doSomeMagic(s.substring(0, s.length() - 1));
}
return toReturn;
}
How can one achieve this with just one function? Any ideas?
I noticed you wanted to do this without a loop and in one function call. You can probably clean this up a lot more. Here it is:
public static String doSomeMagic(String s) {
if (!s.isEmpty()) {
StringBuffer sb = new StringBuffer();
return sb.append(s.replaceAll("(\\S)", "$1$1"))
.append("\n")
.append(doSomeMagic( s.replaceAll(".$", "") )
.toString();
}
return "";
}
To do it in one function, just iterate over the string rather than calling another recursive function.
public static String doSomeMagic(String s) {
String doubled = new String();
if (s.length() == 0) return s;
for(int i=0;i<s.length();i++)
doubled += s.substring(i,i+1) + s.substring(i,i+1)
return doubled + "\n" + doSomeMagic(s.substring(0, s.length()-1));
}
Quick solution could be like
testMethod(string ip){
if(ip.length()==1){
ip=ip.toUppercase();
}
For(int i=0;i<ip.length()-1;i++){
System.out.print(ip.charAt(i)+""+ip.charAt(i));
}
if(ip.length()>1){
System. out. println();
testMethod(ip.substring(1));
}
}
Haven't tested it... But should work fairly