This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have trouble with my code. I need to replace element in Array if condition is true.
Inputs are:
dashedCapital = "------";
input = "a";
capital = "Warsaw";
Code should check if capital contains input and if yes replace "-" in dashedCapital to character from input at specified position:
public static String changeDashedCapital(String dashedCapital, String input, String capital){
String[] capitalArray = capital.split("");
String[] dashedCapitalArray = dashedCapital.split("");
String[] character = input.split("");
for(int i = 0; i < capitalArray.length; i++){
//System.out.println(i);
//System.out.println(capitalArray[i] + character[0] + dashedCapitalArray[i]);
if(capitalArray[i] == character[0]){
dashedCapitalArray[i] = character[0];
}
}
String result = Arrays.toString(dashedCapitalArray);
System.out.println(result);
return result;
}
Result is "------" but should be "-a--a-". What's going wrong?
John, thanks for your reply, it was helpful.
I edited my method so it's look like this now:
public static String changeDashedCapital(String dashedCapital, String input, String capital){
for(int i = 0; i < capital.length(); i++){
if(capital.charAt(i).equals(input.charAt(0))) {
String new_dashed = dashedCapital.substring(0,i)+input.charAt(0)+dashedCapital.substring(i);
System.out.println(new_dashed);
}
}
return "OK:";
Now i get this error:
GetWord.java:69: error: char cannot be dereferenced
if(capital.charAt(i).equals(input.charAt(0))) {
^
1 error
I don't understand why it's wrong. I using a equals() function. I also tried "==" operator but then nothing happens. What does it mean "char cannot be dereferenced"? How I could compare single chars from string with another chars from another string?
The reason it is not working is because your if for character equality is never true. You’re comparing strings of length 1 and not characters. You can quickly fix by changing if be using the string comparing function .equals()
if(capitalArray[i].equals(character[0])){
...
}
However, you should change your code and not just use this fix. Don’t split your stings into arrays, just use the .charAt() method to get a character at a particular index.
Related
This question already has answers here:
How to remove single character from a String by index
(23 answers)
Closed 4 years ago.
To give some context to the title, let's say I have an array of INTs. So, for example (1,2,3,4,5).
Each number in the array represents a char in a string. So if the string is hello then array[3] is going to represent "l".
What is the most efficient or simplest way to remove a char from a string, replace the char and then add it back into the string?
So using the example above I could change "l" to "d", add it back to the string so my final string is "hedlo".
here is part of my code:
method used for max:
public static int getMax(int[] inputArray){
int maxValue = inputArray[0];
for(int i=1;i < inputArray.length;i++){
if(inputArray[i] > maxValue){
maxValue = inputArray[i];
}
}
return maxValue;
}
here is the code for using the max value in the array as the position in the string results to edit. The char to edit should be replaced with an "m" in the actual case
int max = getMax(array);
results.setCharAt(max, 'm');
String result = results.toString();
Yes, it can easiyl be done. Below I have some code from https://stackoverflow.com/a/4576556/9354346
StringBuilder str = new StringBuilder("hello");
str.setCharAt(2, 'd');
String result = str.toString();
Without knowing why you're doing this, I'm not sure exactly what to recommend but here's something to think about. ASCII characters have numerical values associated with them. Table.
If you cast an int to a char, it will convert it to that value. So like,
char c = (char) 97;
would evaluate to 'a.' If you want 'a' to start at 1, you could just add 96 to everything.
To convert, you could add to an int the difference in the table. So from 'a' to 'd', add 3.
EDIT:
I answered this assuming you were changing an array of ints that was representing a string. Re-reading the question, I'm not sure that's what you're doing! If you need to change a character of a string to a different character, you can use the substring function to grab characters before the change, and after the change and put the new character in the middle.
String x = "Hello";
x = x.substring(0,2) + 'd' + x.substring(3);
This makes x say "Hedlo."
This question already has answers here:
Trim leading or trailing characters from a string?
(6 answers)
Closed 5 years ago.
I have the following string and I want to remove dynamic number of dot(.) at the end of the String.
"abc....."
Dot(.) can be more than one
Try this. It uses a regular expression to replace all dots at the end of your string with empty strings.
yourString.replaceAll("\\.+$", "");
Could do this to remove all .:
String a = "abc.....";
String new = a.replaceAll("[.]", "");
Remove just the trailing .'s:
String new = a.replaceAll("//.+$","");
Edit: Seeing the comment. To remove last n .'s
int dotsToRemove = 5; // whatever value n
String new = a.substring(0, s.length()-dotsToRemove);
how about using this function? seems to work faster than regex
public static String trimPoints(String txt)
{
char[] cs = txt.toCharArray();
int index =0;
for(int x =cs.length-1;x>=0;x--)
{
if(cs[x]=='.')
continue;
else
{
index = x+1;
break;
}
}
return txt.substring(0,index);
}
This question already has answers here:
Concatenating null strings in Java [duplicate]
(5 answers)
Closed 7 years ago.
How to add whichever character between every character of a premade String? (JAVA)
For example, I have the String "Hello world" and I have to add '_' between every character of the String.
Any function or useful code I can use to do it?
I have to do an algorithm that make me output "H_e_l_l_o_ _w_o_r_l_d"
This is what I have:
public String example(String s) {
String s2 = null;
for(int i = 0; i < s.length(); i++){
s2 += s.charAt(i) + (((i+1) == 0) ? " " : "-");
}
return s2;
}
My output in the main class is being:
nullH-e-l-l-o- -w-o-r-l-d-
Don't know why
This looks like a homework assignment. So, I won't directly write out all the code.
String = "hello world";
Say, there is a variable len = str.length() - 1. Instead of doing it from index 0, we will start our for loop from len - 1. The character 'd' is at index len, and the '_' will have to be inserted right before that. This can be done by setting the string to str = str.substring(0,i) + "_" + str.substring(i+1);
You will have to use a for loop that starts from len - 1 and goes on till the index reached is 0.
Now, on every single iteration, when you are inserting a character assigning str to str.substring(0,i) + "_" + str.substring(i+1); causes you to make a new string object, which is absolutely horrible style. This can be solved by using a StringBuilder.
Does that make it clear?
In the future, refrain from posting questions without having done any work. This community is there to help you with solving issues that you may have in your solutions, not write your solutions for you.
This question already has answers here:
this method must return a result of type boolean, java
(5 answers)
Closed 7 years ago.
Hi sorry if this is a dumb question, probably is... this is from codingbat (exercise: everNth)
why is it that this works?
public String everyNth(String str, int n) {
String characters = "";
for (int i = 0; i < str.length(); i = i + n) {
characters = characters + Character.toString(str.charAt(i));
}
return characters;
}
but this one doesn't?
public String everyNth(String str, int n) {
for (int i = 0; i < str.length(); i = i + n) {
return Character.toString(str.charAt(i));
}
}
^^ gives me the error: "This method must return a result of type String"
However, doesn't the Character.string() method already create a string?
Why do I have to add in additional quotation marks? Thanks guys!!~~ peace and love
It has nothing to do with the quotation marks. The problem is that you don't have a return statement after the for loop.
The compiler is warning you that if the for loop is never entered, then you will never return anything. You need to make sure your method returns a string value under all circumstances, not just when the loop is entered.
To better understand, walk through your method, and consider what would happen if str has a length of zero. What would your method return then?
EDIT
However, as pointed out by WalterM, keep in mind that, even if you fix the compiler error, your 2nd method's logic is different from your first one. The 2nd method only ever returns the 1st character of the string.
This question already has answers here:
Why does "split" on an empty string return a non-empty array?
(9 answers)
Behaviour of String.split() when input is empty
(2 answers)
Closed 9 years ago.
Here is my code:
serialNumbers = "";
String[] serialArray = serialNumbers.split(",");
int arrayLength = serialArray.length;
arrayLength is showing 1 even there have no value in serialArray. I was expecting that length should return 0 in this case.
From the doc:
If the expression does not match any part of the input then the
resulting array has just one element, namely this string.
Note that this doc is from the String.split(String, int) method, which is invoked from String.split(String)
Split always returns at least one element.
In the case that a separator is not found, the entire input is returned in a single-element array.
serialArray contains [""], which is 1 element
If you look at the implementation of String.class (refer snippet below). Here off shows the match count and this is the String currently being processed for split operation and you have ur string as serialNumbers = "";. Thats why it is returning one item in array.
// If no match was found, return this
if (off == 0)
return new String[]{this};
public class TestArgs {
public static void main(String[] args) {
String checkString = "";
System.out.println("" + splitString(checkString));
}
public static int splitString(String checkString) {
if (checkString.indexOf(",") != -1 || !"".equals(checkString)) {
System.out.println("hello " + checkString.split(",").length);
return checkString.split(",").length;
} else {
return 0;
}
}
}