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);
}
I am trying to split an input like the following:
0-0-1-0;Wolf Blitzer;leaf
with the following code:
public static void buildTree(String treeFile){
//temp string array to hold the input as 3 seperate Strings, seperated by ;
String[] temp= new String[3];
int i=0;
//will split the string into its 3 parts
for (String newTemp: treeFile.split(";")) {
temp[i]=newTemp;
i++;
}
//can hold up to 100 char, each describing a path
char[] pathArray= new char[100];
int pathCursor=0;
i=0;
//once again split the first part of the string, which holds the path, into an array of chars,
//parse each String into a char and then set equal to in array in array
for(String newTemp: temp[0].split("-")){
char c=newTemp.charAt(0);
pathArray[i]=c;
i++;
pathCursor++;
}
for(int j=0; j<3;j++){
System.out.println(temp[j]);
}
for(int j=0; j<pathCursor;j++){
System.out.println(pathArray[j]);
}
}
When I encounter spaces such as the the space in Wolf Blitzer, or periods in titles such as Dr. Strange, my split function doesn't work correctly. I thought that it would only split at whatever character I defined (in this case the ; and later the -). Am I not understanding split() correctly?
EDIT:
My expected output should be:
0-0-1-0
Wolf Blitzer
Leaf
0
0
1
0
Also I am trying to diagnose the issue and therefore am manually passing in the TreeFile with a simple test file which just asks for a string and then calls the method
I want to return words from a String array one after the other.
public String CurrentString(int move) {
int currentString = 0;
EditText ed = (EditText) findViewById(R.id.ed);
String[] strings = ed.getText().toString().split(" ");
int newString = currentString move;
if (newString >= strings.length) {
// if the new position is past the end of the array, go back to the beginning
newString = 0;
}
if (newString < 0) {
// if the new position is before the beginning, loop to the end
newString = strings.length - 1;
}
currentString = newString;
Toast.makeText(getApplicationContext(), strings[currentString],Toast.LENGTH_LONG).show();
return strings[currentString];
}
The problem is that my above code doesn't return all texts. Please, help.
Seems you have not done enough "homework" and are having problems with arrays, (that's why people are down-voting [this is not a site for beginners who not do put in the required "research effort", the site would be inundated]).
The current trend is to downvote AND/OR leave a sarcastic comment ;O)
Also your code contains errors that will not compile, so you have not even bothered to test it ! ;O(
Lucky for you you cannot get a negative reputation !
Seriously please do some research (google it !)
Here is some code that may help. Use split to process your string into a string array:
String string = "I want a string array of all these words";//input string
// ^ ^ ^ ^ ^ ^ ^ ^ ^
// 0 1 2 3 4 5 6 7 8 //index
String[] array_of_words;//output array of words
array_of_words = CurrentString(string);//execute method
Log.i("testing", array_of_words[8]);//this would be "words" in this example
//later you might want to process commas and full stops etc...
public String[] CurrentString(String string)
{
String[] array = string.split(" "); //use space to split string into words
//With the advent of Java 5, we can make our for loops a little cleaner and easier to read
for ( String sarray : array ) //loop through String array
{
Log.i("CurrentString", sarray );//print the words
}
return array ;//return String array
}
So i'm trying to reverse a sentence and even though I don't have any errors when compiling, it tells me my reverse sentence is out of bounds.
-It should work like this: "hello, world!" --> !dlrow ,olleh"
Said code:
String sentence="this is a sentence!";
String reverseSentence=sentence;
for(int counter=0;counter<sentence.length();counter++)
{
char charToReplace,replaceChar;
charToReplace = reverseSentence.charAt(counter);
replaceChar = sentence.charAt(sentence.length()-counter);
reverseSentence=reverseSentence.replace(charToReplace, replaceChar);
System.out.println(reverseSentence);
}
The reason for the exception you are getting is that in sentence.charAt(sentence.length()-counter), sentence.length()-counter is out of bounds when counter is 0. Should be sentence.length()-1-counter.
However, as Tunaki commented, there are other problems with your code. I suggest you use a StringBuilder to construct the reversed String, instead of using replace (which would replace any occurrence of the first character with the second character).
You can use character arrays to implement your requirement like this,
String sentence = "ABDEF";
char[] firstString = sentence.toCharArray();
char[] reversedString = new char[sentence.length()];
for (int counter = 0; counter < sentence.length(); counter++) {
reversedString[counter] = firstString[sentence.length() - counter -1];
}
System.out.println(String.copyValueOf(reversedString));
It doesn't show you an error because the Exception concerning the indexes happen at RunTime.
Here :
replaceChar = sentence.charAt(sentence.length()-counter);
You're trying to access index 19 of your String (19-0). Replace it with :
replaceChar = sentence.charAt(sentence.length()-counter-1);
I'd recommend to use a StringBuilder in your situation though.
Either use the reverse() method :
String sentence = "this is a sentence!";
String reversed = new StringBuilder(sentence).reverse().toString();
System.out.println(reversed); // Prints : !ecnetnes a si siht
Or use the append() method for building your new String object. This uses less memory than using a String because it is not creating a new String object each time you're looping :
String sentence = "this is a sentence!";
StringBuilder reversed = new StringBuilder();
for (int i = 0 ; i < sentence.length() ; i++){
reversed.append(sentence.charAt(sentence.length() - 1 - i));
}
System.out.println(reversed.toString()); // Prints : !ecnetnes a si siht
It maybe better to do it without any replacement, or for loop. It you create a char array from the string, reverse the array, then create a string from the reversed array this would do what you've asked without any moving parts or replacements. For example:
String hw = "hello world";
char[] hwChars = hw.toCharArray();
ArrayUtils.reverse(hwChars);
String wh = new String(hwChars);
System.out.println(wh);
Just split the String at each whitespace and put it in String array and then print the array in reverse order
public static void main(String[] args) {
String sentence = "this is a sentence!";
String[] reverseSentence = sentence.split(" ");
for (int i = reverseSentence.length-1; i >= 0; i--) {
System.out.print(" " + reverseSentence[i]);
}
}
I'm porting a Hangman game to Android and have met a few problems. The original Java program used the console, so now I have to somehow beautify the output so that it fits my Android layout.
How do I print an array without the brackets and commas? The array contains slashes and gets replaced one-by-one when the correct letter is guessed.
I am using the usual .toString() function of the ArrayList class and my output is formatted like: [ a, n, d, r, o, i, d ]. I want it to simply print out the array as a single String.
I fill the array using this bit of code:
List<String> publicArray = new ArrayList<>();
for (int i = 0; i < secretWordLength; i++) {
hiddenArray.add(secretWord.substring(i, i + 1));
publicArray.add("-");
}
And I print it like this:
TextView currentWordView = (TextView) findViewById(R.id.CurrentWord);
currentWordView.setText(publicArray.toString());
Replace the brackets and commas with empty space.
String formattedString = myArrayList.toString()
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.trim(); //remove trailing spaces from partially initialized arrays
Basically, don't use ArrayList.toString() - build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray when it's not actually an array, by the way.)
For Android, you can use the join method from android.text.TextUtils class like:
TextUtils.join("",array);
first
StringUtils.join(array, "");
second
Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")
EDIT
probably the best one: Arrays.toString(arr)
With Java 8 or newer, you can use String.join, which provides the same functionality:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter
String[] array = new String[] { "a", "n", "d", "r", "o", "i", "d" };
String joined = String.join("", array); //returns "android"
With an array of a different type, one should convert it to a String array or to a char sequence Iterable:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
//both of the following return "1234567"
String joinedNumbers = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).toArray(n -> new String[n]));
String joinedNumbers2 = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).collect(Collectors.toList()));
The first argument to String.join is the delimiter, and can be changed accordingly.
If you use Java8 or above, you can use with stream() with native.
publicArray.stream()
.map(Object::toString)
.collect(Collectors.joining(" "));
References
Use Java 8 Language Features
JavaDoc StringJoiner
Joining Objects into a String with Java 8 Stream API
the most simple solution for removing the brackets is,
convert the arraylist into string with .toString() method.
use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).
the result string is your string with removed brackets.
I have used
Arrays.toString(array_name).replace("[","").replace("]","").replace(", ","");
as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.
I used join() function like:
i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");
Which Prints:
HiHelloCheersGreetings
See more: Javascript Join - Use Join to Make an Array into a String in Javascript
String[] students = {"John", "Kelly", "Leah"};
System.out.println(Arrays.toString(students).replace("[", "").replace("]", " "));
//output: John, Kelly, Leah
You can use the reduce method provided for streams for Java 8 and above.Note you would have to map to string first to allow for concatenation inside of reduce operator.
publicArray.stream().map(String::valueOf).reduce((a, b) -> a + " " + b).get();
I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.
Please refer to my Code & Output below:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
System.out.println("Enter Value " + i + " to add: ");
mylist.add(scan.nextLine());
}
System.out.println("=======================");
for(int j = 0; j < 5; j++) {
System.out.print(mylist.get(j));
}
}
}
OUTPUT
Enter Value 0 to add:
1
Enter Value 1 to add:
2
Enter Value 2 to add:
3
Enter Value 3 to add:
4
Enter Value 4 to add:
5
=======================
12345
Just initialize a String object with your array
String s=new String(array);