This question already has answers here:
How to Replace dot (.) in a string in Java
(4 answers)
Closed 2 years ago.
I have following problem with java.This method in Class should return String as is.
private String getAsString(Resource res) {
return "We wish you good luck in this exam!\nWe hope you are well pre-\npared.";
}
Then in Constructor this String shlud be converted into array of words
private int index;
private String string_arr[];
public TextFileIterator(Resource res) {
this.index=0;
if(res==null){
throw new NullPointerException();
}
String text=this.getAsString(res);
//text=text.replaceAll("-\n(?=[a-z])", "");
text=text.replaceAll("\\n", "");
text=text.replaceAll("!", " ");
text=text.replaceAll("-", "");
text=text.replaceAll(".", "");
this.string_arr=text.split(" ");
}
Problem is that at the end I get array which is null... what is the problem. I attach the debugger screenshots.
Please could explain me why does it happen?
The culprit is line no 17-
text=text.replaceAll(".", "");
The above line is replacing all of the content with "", because in regex world "." means any character.
Try this instead-
text=text.replaceAll("\\.", "");
Related
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.
This question already has answers here:
Find the Number of Occurrences of a Substring in a String
(27 answers)
Closed 5 years ago.
String str = "ABthatCDthatBHthatIOthatoo";
System.out.println(str.split("that").length-1);
From this I got 4. that is right but if last that doesn't have any letter after it then it shows wrong answer '3' as in :
String str = "ABthatCDthatBHthatIOthat";
System.out.println(str.split("that").length-1);
I want to count the occurrence of "that" word in given String.
You could specify a limit to account for the final 'empty' token
System.out.println(str.split("that", -1).length-1);
str.split("that").length doesn't count the number of 'that's . It counts the
number of words that have 'that' in between them
For example-
class test
{
public static void main(String args[])
{
String s="Hi?bye?hello?goodDay";
System.out.println(s.split("?").length);
}
}
This will return 4, which is the number of words separated by "?".
If you return length-1, in this case, it will return 3, which is the correct count of the number of question marks.
But, what if the String is : "Hi????bye????hello?goodDay??"; ?
Even in this case, str.split("?").length-1 will return 3, which is the incorrect count of the number of question marks.
The actual functionality of str.split("that //or anything") is to make a String array which has all those characters/words separated by 'that' (in this case).The split() function returns a String array
So, the above str.split("?") will actually return a String array : {"Hi,bye,hello,goodDay"}
str.split("?").length is returning nothing but the length of the array which has all the words in str separated by '?' .
str.split("that").length is returning nothing but the length of the array which has all the words in str separated by 'that' .
Here is my link for the solution of the problem link
Please tell me if you have any doubt.
Find out position of substring "that" using lastIndexOf() and if its at last position of the string then increment the cout by 1 of your answer.
Try this
String fullStr = "ABthatCDthatBHthatIOthatoo";
String that= "that";
System.out.println(StringUtils.countMatches(fullStr, that));
use StringUtils from apache common lang, this one https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/src-html/org/apache/commons/lang/StringUtils.html#line.170
I hope this would help
public static void main(String[] args) throws Exception
{ int count = 0;
String str = "ABthatCDthatBHthatIOthat";
StringBuffer sc = new StringBuffer(str);
while(str.contains("that")){
int aa = str.indexOf("that");
count++;
sc = sc.delete(aa, aa+3);
str = sc.toString();
}
System.out.println("count is:"+count);
}
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:
Check and extract a number from a String in Java
(16 answers)
Closed 5 years ago.
how do I check if a string contains a digit?
public static void main(String[] args)
{
s1 = "Hello32"; //should be true`enter code here`
s2 = "He2llo"; //should be true
s3 = "Hello"; //should be false
}
With a regex you could search at least a digit among any (zero or more) characters:
boolean hasDigit = s1.matches(".*\\d+.*");
Check this it might help you
String regex = "\\d+";
System.out.println("abc45hdg".matches(regex));
In java
public boolean containsNumber(String string)
{
return string.matches(".*\\d+.*");
}
This question already has answers here:
String replace method is not replacing characters
(5 answers)
Closed 7 years ago.
Maybe I am using replaceAll incorrectly, but I am unable to find why it acts this way. I want to simply remove a $ sign from a string and then output the string.
public class Example{
public static void main(String[] args){
String s = "$50";
s.replaceAll("\\D+", "");
System.out.println(s);
}
}
However, this still outputs the $ symbol with the string. Does anyone know why this is happening?
You need to assign the return value of replaceAll to a variable:
s = s.replaceAll("\\D+", "");
because a String object is immutable.