Split a String into number of Characters desired by the user - java

I want to split a String into n number of characters.
Consider input to be "Example-for-my-Question". Now if I want to split into n=3 characters, output should be "Exa, mpl, e-f, or-, my-, Que, sti, on" and suppose n=4, output should be "Exam, ple-, for-, my-Q, uest, ion" How can you modify the program below without using POSIX.
import java.util.Scanner;
public class SplitString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String; ");
String inputString = in.nextLine();
System.out.println("How many characters do you want to split into ?");
int n = in.nextInt();
String[] array = inputString.split(" ", n);
System.out.println("Number of words: " + array.length);
for (String arr : array)
System.out.println(arr);
}
}

The simple way to do this is to use String.substring(...) repeatedly to trim N characters off the front of your string ... in a loop.
But if you really want to do this using String.split(...), then I think that the separator regex needs to be a positive look-behind that matches N characters. (It is obscure, and inefficient ... but if regexes are your universal tool ...)

You can use substring for this task.
String sp="StackOverFlow";
int NoOfChars=3;
for(int i=0;i<sp.length();i+=NoOfChars)
{
if(i+NoOfChars<=sp.length())
System.out.println(sp.substring(i,i+NoOfChars));
//Instead add in String ArrayList
else
System.out.println(sp.substring(i));
}
OUTPUT
Sta
ckO
ver
Flo
w
NOTE:Better to use trim() to remove leading or trailing spces

This works for me. In addition to splitting into known lengths, it checks for a null or "too small of a" source string, etc. If a null string is supplied, then a null is returned. If the source string is smaller than the requested split length, then the source string is simply returned.
public static void main (String[] args) throws java.lang.Exception
{
// Three test cases...
String pieces[] = SplitString("Example-for-my-Question", 3);
//String pieces[] = SplitString("Ex", 3);
//String pieces[] = SplitString(null, 3);
if (null != pieces)
{
for (int i = 0; i < pieces.length; i++)
{
System.out.println(pieces[i]);
}
}
}
private static String[] SplitString(String source, int size)
{
String result[] = null;
if (null != source && source.length() > size)
{
int numberOfElements = source.length() / size;
int modulo = source.length() % size;
if (modulo > 0)
{
numberOfElements++;
}
result = new String[numberOfElements];
for (int i = 0; i < numberOfElements; i++)
{
if (numberOfElements - 1 != i)
{
result[i] = source.substring(i * size, (i * size) + size);
}
else
{
result[numberOfElements - 1] = source.substring(i * size, (i * size) + modulo);
}
}
}
else if (null != source)
{
result = new String[1];
result[0] = source;
}
return result;
}

Please try the following program, but here you have to give input to "N" inside the program itself
class Main {
public static void main(String[] args) {
int N = 5;
String text = "aaaaabbbbbccccceeeeefff";
String[] tokens = text.split("(?<=\\G.{" + N + "})");
for(String t : tokens) {
System.out.println(t);
}
}
}

Related

Checking numbers in a string

Notice: I know that there are tons of ways to make this simpler, but it is not allowed. I am bounded to plain, basic java, loops and hand written methods.
Even arrays are not allowed.Regex as well.
Task is to check for numbers in each word of a sentence,find the word with the greatest number which is at the same time POWER OF 3.
I did everything here and it works fine until I enter something like this.
asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125
I receive output 64 instead of 125, because it stops checking when it reaches first number WHICH IS NOT POWER OF 3.
How can I continue the iteration till the end of my sentence and avoid stopping when I reach non power of 3 number ,how to modify this code to achieve that ?
Edit: But if I enter more than one word after the one that FAILS THE CONDITION, it will work just fine.
for instance:
asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125 asdash216
Here is my code:
public class Nine {
static int num(String s) { // method to change string to int
int b = 0;
int o = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char bi = s.charAt(i);
b += (bi - '0') * (int) Math.pow(10, o);
o++;
}
return b;
}
static boolean thirdPow(int a) {
boolean ntrec = false;
if (Math.cbrt(a) % 1 == 0)
ntrec = true;
return ntrec;
}
static int max(int a, int b) {
int max= 0;
if (a > b)
max= a;
else
max= b;
System.out.print(max);
return max;
}
static String search(String r) {
String current= ""; // 23aa64
String currentA= "";
String br = ""; // smjestamo nas broj iz rijeci 23
int bb = 0; // nas pretvoreni string u broj
int p = 0;
for (int i = 0; i < r.length(); i++) {
current+= r.charAt(i);
if (r.charAt(i) == ' ') {
for (int j = 0; j < current.length(); j++) {
while ((int) current.charAt(j) > 47 && (int) current.charAt(j) < 58) {
br += current.charAt(j);
j++;
}
bb = num(br);
System.out.println("Third pow" + thirdPow(bb));
if (thirdPow(bb)) {
p = max(p, bb);
}
br = "";
}
current= "";
}
}
String pp = "" + p;
String finalRes= "";
for (int u = 0; u < r.length(); u++) {
currentA+= r.charAt(u);
if (r.charAt(u) == ' ') {
if (currentA.contains(pp))
finalRes+= currentA;
currentA= "";
}
}
System.out.println(p);
return finalRes;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter sentence: ");
String r = scan.nextLine();
System.out.println("Our string is : " + search(r));
}
}
I am assuming that each word is separated by an empty space and containing non-Integers.
Usage of regular expressions will certainly reduce the code complexity, Let's try this code: -
String input = "asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125";
String[] extractWords = r.split(" "); //extracting each words
int[] numbers = new int[extractWords.length]; // creating an Integer array to store numbers from each word
int i=0;
for(String s : extractWords) {
numbers[i++] = Integer.parseInt(s.replaceAll("\\D+", "")); // extracting numbers
}
Now, the "numbers" array will contain [8, 27, 64, 333, 125]
You can use your logic to find a maximum among them. Hope this helps.
You can just do what I am doing. First split the sentence to chunks of words. I am doing it based on spaces, hence the in.split("\\s+"). Then find the numbers from these words. On these numbers check for the highest number only if it is a power of 3.
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
static boolean isPowOfThree(int num)
{
int temp = (int)Math.pow(num, 1f/3);
return (Math.pow(temp, 3) == num);
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
String in = sc.nextLine();
String[] words = in.split("\\s+");
String maxWord = ""; //init default word
int maxNum = -1; //init default num
for(String word : words)
{
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(word);
while (m.find())
{
String num = m.group();
if(isPowOfThree(Integer.parseInt(num)))
{
if(Integer.parseInt(num) > maxNum)
{
maxNum = Integer.parseInt(num);
maxWord = word;
}
}
}
}
if(maxNum > -1)
{
System.out.println("Word is : " + maxWord);
}
else
{
System.out.println("No word of power 3");
}
}
}
The problem can be solved using \\d+ regular expression with Matcher and Pattern API in Java.
package com.company;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String i = "asdas8 dasjkj278 asdjkj64 asdjk333 asdjkj125";
Matcher matcher = Pattern.compile("\\d+").matcher(i);
List<Integer> numbers = new ArrayList<>();
while (matcher.find()){
numbers.add(Integer.parseInt(matcher.group()));
}
Collections.sort(numbers);
Collections.reverse(numbers);
Integer power3 = 0;
for (Integer n : numbers) {
if (isPowOfThree(n)) {
power3 = n;
break;
}
}
System.out.println(power3);
}
static boolean isPowOfThree(int num) {
int temp = (int)Math.pow(num, 1f/3);
return (Math.pow(temp, 3) == num);
}
}
Upon using \\d+ regular expression we get all the digits in the given string for every iteration of while(matcher.find()). Once we collect all the numbers in the given string, we need to reverse sort the collection. If we iterate over this collection, the first number that we find is the largest number which is a power of 3, since the collection is already sorted in descending order.
Brother use
*string.split(" ");*
to form an array of strings and then iterate through the array and parse the numbers using regex
^[0-9]
or
\d+
and then find the biggest number from the array as simple as that. Brother proceeds step by step then your code will run faster.

Rotating a Sentence by n words

I'm am trying to update a code that I have previously written to "rotate a String." Currently my program accepts a string from keyboard input and an integer n. ex. "abcdefg", 3. Then rotates the string by n characters before returning the rotated string i.e. "efgabcd". Now for the tricky part. I'm trying to update this to do essentially the same thing but with a sentence. So the inputs would be a something like "This is an example" and an integer 3. then the output would be "is an example this." I assume splitting the sentence into an array would be my best bet; however my unfamiliarity with strings doesn't allow my to know how to go about doing this.
import java.util.*;
public class Rotate
{
public static String rotate(String s, int num)
{
int length = s.length();
String a = s.substring(0,(length-num));
String b = s.substring((length-num),length);
String c = b + a;
return c;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a string:");
String s = input.nextLine();
System.out.print("Enter the number of characters that you want to rotated to right:");
int n =input.nextInt();
String t = rotate(s, n);
System.out.println("The rotated string is "+ t);
}
}
Here's a sample solution:
int num = 3;
String str = "This is a test";
String[] strArr = str.split(" ");
int length = strArr.length;
String[] temp = Arrays.copyOfRange(strArr, length - num, length);
System.arraycopy(strArr, 0, strArr, num, length - num);
System.arraycopy(temp, 0, strArr, 0, temp.length);
str = String.join(" ", strArr);
str now contains "is a test This".
EDIT: Fixed to rotate to right.
I actually prefer #fergDEV's solution, but it can be cleaned up a bit if you're using Java 8:
int num = 3;
String str = "This is a test";
List<String> parts = Arrays.asList(str.split(" "));
Collections.rotate(parts, 3);
String.join(" ", parts);
The Collections utils are your friend :P.
public class Main {
public static String rotateSetence(final String input, final int rotation) {
final List<String> results = Arrays.asList(input.split(" "));
Collections.rotate(results, rotation);
final StringBuilder outputBuilder = new StringBuilder();
for (int i = 0; i < results.size(); i++) {
outputBuilder.append(results.get(i));
if (i != results.size() - 1)
outputBuilder.append(" ");
}
return outputBuilder.toString();
}
public static void main(String[] args) {
final String inputString = "This is an example";
final int sentenceRotation = 3;
final String expectedResult = "is an example This";
final String result = rotateSetence(inputString, sentenceRotation);
System.out.println("result " + result);
if (result.equals(expectedResult)) {
System.out.println("Passed");
} else {
System.out.println("Failed");
}
}
}
EDIT
The builder code can be replaced with string.join ... thanks to #shmosel.
final StringBuilder outputBuilder = new StringBuilder();
for (int i = 0; i < results.size(); i++) {
outputBuilder.append(results.get(i));
if (i != results.size() - 1)
outputBuilder.append(" ");
}
return outputBuilder.toString();
can be replaced with
return String.join(" ", results);
You can also make use of two for loops, such that in the first for loop you loop from num (provided by user) position to the end of the string. And in the second loop you loop from start of string until the position of num.
For above logic to work, you obviously need to split your string using space into array of strings. See below:
public static String rotate(String s, int num)
{
//split the sentence by space
String[] chunks = s.split(" ");
//use StringBuilder to build rotated string
StringBuilder builder = new StringBuilder();
//loop from position specified by user to end of array
for(int i = num; i < chunks.length; i++) {
builder.append(chunks[i] + " ");
}
//loop from start of array to position specified by user
for(int i = 0; i < num; i++) {
builder.append(chunks[i] + " ");
}
return builder.toString();
}
The input and output is shown below:
Enter a string:My name is Raf and I am super super fun guy trust me
Enter the number of characters that you want to rotated to right:2
The rotated string is : is Raf and I am super super fun guy trust me My name

Java words reverse

I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}

Count the number of Occurrences of a Word in a String

I am new to Java Strings the problem is that I want to count the Occurrences of a specific word in a String. Suppose that my String is:
i have a male cat. the color of male cat is Black
Now I dont want to split it as well so I want to search for a word that is "male cat". it occurs two times in my string!
What I am trying is:
int c = 0;
for (int j = 0; j < text.length(); j++) {
if (text.contains("male cat")) {
c += 1;
}
}
System.out.println("counter=" + c);
it gives me 46 counter value! So whats the solution?
You can use the following code:
String in = "i have a male cat. the color of male cat is Black";
int i = 0;
Pattern p = Pattern.compile("male cat");
Matcher m = p.matcher( in );
while (m.find()) {
i++;
}
System.out.println(i); // Prints 2
Demo
What it does?
It matches "male cat".
while(m.find())
indicates, do whatever is given inside the loop while m finds a match.
And I'm incrementing the value of i by i++, so obviously, this gives number of male cat a string has got.
If you just want the count of "male cat" then I would just do it like this:
String str = "i have a male cat. the color of male cat is Black";
int c = str.split("male cat").length - 1;
System.out.println(c);
and if you want to make sure that "female cat" is not matched then use \\b word boundaries in the split regex:
int c = str.split("\\bmale cat\\b").length - 1;
StringUtils in apache commons-lang have CountMatches method to counts the number of occurrences of one String in another.
String input = "i have a male cat. the color of male cat is Black";
int occurance = StringUtils.countMatches(input, "male cat");
System.out.println(occurance);
Java 8 version:
public static long countNumberOfOccurrencesOfWordInString(String msg, String target) {
return Arrays.stream(msg.split("[ ,\\.]")).filter(s -> s.equals(target)).count();
}
Java 8 version.
System.out.println(Pattern.compile("\\bmale cat")
.splitAsStream("i have a male cat. the color of male cat is Black")
.count()-1);
This static method does returns the number of occurrences of a string on another string.
/**
* Returns the number of appearances that a string have on another string.
*
* #param source a string to use as source of the match
* #param sentence a string that is a substring of source
* #return the number of occurrences of sentence on source
*/
public static int numberOfOccurrences(String source, String sentence) {
int occurrences = 0;
if (source.contains(sentence)) {
int withSentenceLength = source.length();
int withoutSentenceLength = source.replace(sentence, "").length();
occurrences = (withSentenceLength - withoutSentenceLength) / sentence.length();
}
return occurrences;
}
Tests:
String source = "Hello World!";
numberOfOccurrences(source, "Hello World!"); // 1
numberOfOccurrences(source, "ello W"); // 1
numberOfOccurrences(source, "l"); // 3
numberOfOccurrences(source, "fun"); // 0
numberOfOccurrences(source, "Hello"); // 1
BTW, the method could be written in one line, awful, but it also works :)
public static int numberOfOccurrences(String source, String sentence) {
return (source.contains(sentence)) ? (source.length() - source.replace(sentence, "").length()) / sentence.length() : 0;
}
using indexOf...
public static int count(String string, String substr) {
int i;
int last = 0;
int count = 0;
do {
i = string.indexOf(substr, last);
if (i != -1) count++;
last = i+substr.length();
} while(i != -1);
return count;
}
public static void main (String[] args ){
System.out.println(count("i have a male cat. the color of male cat is Black", "male cat"));
}
That will show: 2
Another implementation for count(), in just 1 line:
public static int count(String string, String substr) {
return (string.length() - string.replaceAll(substr, "").length()) / substr.length() ;
}
Why not recursive ?
public class CatchTheMaleCat {
private static final String MALE_CAT = "male cat";
static int count = 0;
public static void main(String[] arg){
wordCount("i have a male cat. the color of male cat is Black");
System.out.println(count);
}
private static boolean wordCount(String str){
if(str.contains(MALE_CAT)){
count++;
return wordCount(str.substring(str.indexOf(MALE_CAT)+MALE_CAT.length()));
}
else{
return false;
}
}
}
public class TestWordCount {
public static void main(String[] args) {
int count = numberOfOccurences("Alice", "Alice in wonderland. Alice & chinki are classmates. Chinki is better than Alice.occ");
System.out.println("count : "+count);
}
public static int numberOfOccurences(String findWord, String sentence) {
int length = sentence.length();
int lengthWithoutFindWord = sentence.replace(findWord, "").length();
return (length - lengthWithoutFindWord)/findWord.length();
}
}
This will work
int word_count(String text,String key){
int count=0;
while(text.contains(key)){
count++;
text=text.substring(text.indexOf(key)+key.length());
}
return count;
}
Replace the String that needs to be counted with empty string and then use the length without the string to calculate the number of occurrence.
public int occurrencesOf(String word)
{
int length = text.length();
int lenghtofWord = word.length();
int lengthWithoutWord = text.replace(word, "").length();
return (length - lengthWithoutWord) / lenghtofWord ;
}
Once you find the term you need to remove it from String under process so that it won't resolve the same again, use indexOf() and substring() , you don't need to do contains check length times
The string contains that string all the time when looping through it. You don't want to ++ because what this is doing right now is just getting the length of the string if it contains " "male cat"
You need to indexOf() / substring()
Kind of get what i am saying?
If you find the String you are searching for, you can go on for the length of that string (if in case you search aa in aaaa you consider it 2 times).
int c=0;
String found="male cat";
for(int j=0; j<text.length();j++){
if(text.contains(found)){
c+=1;
j+=found.length()-1;
}
}
System.out.println("counter="+c);
This should be a faster non-regex solution.
(note - Not a Java programmer)
String str = "i have a male cat. the color of male cat is Black";
int found = 0;
int oldndx = 0;
int newndx = 0;
while ( (newndx=str.indexOf("male cat", oldndx)) > -1 )
{
found++;
oldndx = newndx+8;
}
There are so many ways for the occurrence of substring and two of theme are:-
public class Test1 {
public static void main(String args[]) {
String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc a ";
count(st, 0, "a".length());
}
public static void count(String trim, int i, int length) {
if (trim.contains("a")) {
trim = trim.substring(trim.indexOf("a") + length);
count(trim, i + 1, length);
} else {
System.out.println(i);
}
}
public static void countMethod2() {
int index = 0, count = 0;
String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
String subString = "my".toLowerCase();
while (index != -1) {
index = inputString.indexOf(subString, index);
if (index != -1) {
count++;
index += subString.length();
}
}
System.out.print(count);
}}
We can count from many ways for the occurrence of substring:-
public class Test1 {
public static void main(String args[]) {
String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc a ";
count(st, 0, "a".length());
}
public static void count(String trim, int i, int length) {
if (trim.contains("a")) {
trim = trim.substring(trim.indexOf("a") + length);
count(trim, i + 1, length);
} else {
System.out.println(i);
}
}
public static void countMethod2() {
int index = 0, count = 0;
String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
String subString = "my".toLowerCase();
while (index != -1) {
index = inputString.indexOf(subString, index);
if (index != -1) {
count++;
index += subString.length();
}
}
System.out.print(count);
}}
I've got another approach here:
String description = "hello india hello india hello hello india hello";
String textToBeCounted = "hello";
// Split description using "hello", which will return
//string array of words other than hello
String[] words = description.split("hello");
// Get number of characters words other than "hello"
int lengthOfNonMatchingWords = 0;
for (String word : words) {
lengthOfNonMatchingWords += word.length();
}
// Following code gets length of `description` - length of all non-matching
// words and divide it by length of word to be counted
System.out.println("Number of matching words are " +
(description.length() - lengthOfNonMatchingWords) / textToBeCounted.length());
Complete Example here,
package com.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class WordsOccurances {
public static void main(String[] args) {
String sentence = "Java can run on many different operating "
+ "systems. This makes Java platform independent.";
String[] words = sentence.split(" ");
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
for (int i = 0; i<words.length; i++ ) {
if (wordsMap.containsKey(words[i])) {
Integer value = wordsMap.get(words[i]);
wordsMap.put(words[i], value + 1);
} else {
wordsMap.put(words[i], 1);
}
}
/*Now iterate the HashMap to display the word with number
of time occurance */
Iterator it = wordsMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> entryKeyValue = (Map.Entry<String, Integer>) it.next();
System.out.println("Word : "+entryKeyValue.getKey()+", Occurance : "
+entryKeyValue.getValue()+" times");
}
}
}
public class WordCount {
public static void main(String[] args) {
// TODO Auto-generated method stub
String scentence = "This is a treeis isis is is is";
String word = "is";
int wordCount = 0;
for(int i =0;i<scentence.length();i++){
if(word.charAt(0) == scentence.charAt(i)){
if(i>0){
if(scentence.charAt(i-1) == ' '){
if(i+word.length()<scentence.length()){
if(scentence.charAt(i+word.length()) != ' '){
continue;}
}
}
else{
continue;
}
}
int count = 1;
for(int j=1 ; j<word.length();j++){
i++;
if(word.charAt(j) != scentence.charAt(i)){
break;
}
else{
count++;
}
}
if(count == word.length()){
wordCount++;
}
}
}
System.out.println("The word "+ word + " was repeated :" + wordCount);
}
}
Simple solution is here-
Below code uses HashMap as it will maintain keys and values. so here keys will be word and values will be count (occurance of a word in a given string).
public class WordOccurance
{
public static void main(String[] args)
{
HashMap<String, Integer> hm = new HashMap<>();
String str = "avinash pande avinash pande avinash";
//split the word with white space
String words[] = str.split(" ");
for (String word : words)
{
//If already added/present in hashmap then increment the count by 1
if(hm.containsKey(word))
{
hm.put(word, hm.get(word)+1);
}
else //if not added earlier then add with count 1
{
hm.put(word, 1);
}
}
//Iterate over the hashmap
Set<Entry<String, Integer>> entry = hm.entrySet();
for (Entry<String, Integer> entry2 : entry)
{
System.out.println(entry2.getKey() + " "+entry2.getValue());
}
}
}
public int occurrencesOf(String word) {
int length = text.length();
int lenghtofWord = word.length();
int lengthWithoutWord = text.replaceAll(word, "").length();
return (length - lengthWithoutWord) / lenghtofWord ;
}
for scala it's just 1 line
def numTimesOccurrenced(text:String, word:String) =text.split(word).size-1

how to split a string by position in Java

I did not find anywhere an answer.. If i have: String s = "How are you"?
How can i split this into two strings, so first string containing from 0..s.length()/2 and the 2nd string from s.length()/2+1..s.length()?
Thanks!
This should do:
String s = "How are you?";
String first = s.substring(0, s.length() / 2); // gives "How ar"
String second = s.substring(s.length() / 2); // gives "e you?"
String.substring(int i) with one argument returns the substring beginning at position i
String.substring(int i, int j) with two arguments returns the substring beginning at i and ending at j-1.
(Note that if the length of the string is odd, second will have one more character than first due to the rounding in the integer division.)
String s0 = "How are you?";
String s1 = s0.subString(0, s0.length() / 2);
String s2 = s0.subString(s0.length() / 2);
So long as s0 is not null.
EDIT
This will work for odd length strings as you are not adding 1 to either index. Surprisingly it even works on a zero length string "".
You can use 'substring(start, end)', but of course check if string isn't null before:
String first = s.substring(0, s.length() / 2);
String second = s.substring(s.length() / 2);
http://www.roseindia.net/java/beginners/SubstringExample.shtml
And are you expecting string with odd length ? in this case you must add logic to handle this case correctly.
Here's a method that splits a string into n items by length. (If the string length can not exactly be divided by n, the last item will be shorter.)
public static String[] splitInEqualParts(final String s, final int n){
if(s == null){
return null;
}
final int strlen = s.length();
if(strlen < n){
// this could be handled differently
throw new IllegalArgumentException("String too short");
}
final String[] arr = new String[n];
final int tokensize = strlen / n + (strlen % n == 0 ? 0 : 1);
for(int i = 0; i < n; i++){
arr[i] =
s.substring(i * tokensize,
Math.min((i + 1) * tokensize, strlen));
}
return arr;
}
Test code:
/**
* Didn't use Arrays.toString() because I wanted to have quotes.
*/
private static void printArray(final String[] arr){
System.out.print("[");
boolean first = true;
for(final String item : arr){
if(first) first = false;
else System.out.print(", ");
System.out.print("'" + item + "'");
}
System.out.println("]");
}
public static void main(final String[] args){
printArray(splitInEqualParts("Hound dog", 2));
printArray(splitInEqualParts("Love me tender", 3));
printArray(splitInEqualParts("Jailhouse Rock", 4));
}
Output:
['Hound', ' dog']
['Love ', 'me te', 'nder']
['Jail', 'hous', 'e Ro', 'ck']
Use String.substring(int), and String.substring(int, int) method.
int cutPos = s.length()/2;
String s1 = s.substring(0, cutPos);
String s2 = s.substring(cutPos, s.length()); //which is essentially the same as
//String s2 = s.substring(cutPos);
I did not find anywhere an answer.
The first place you should always look is at the javadocs for the class in question: in this case java.lang.String. The javadocs
can be browsed online on the Oracle website (e.g. at http://download.oracle.com/javase/6/docs/api/),
are included in any Sun/Oracle Java SDK distribution,
are probably viewable in your Java IDE, and
and be found using a Google search.
public int solution(final String S, final int K) {
int splitCount = -1;
final int count = (int) Stream.of(S.split(" ")).filter(v -> v.length() > K).count();
if (count > 0) {
return splitCount;
}
final List<String> words = Stream.of(S.split(" ")).collect(Collectors.toList());
final List<String> subStrings = new ArrayList<>();
int counter = 0;
for (final String word : words) {
final StringJoiner sj = new StringJoiner(" ");
if (subStrings.size() > 0) {
final String oldString = subStrings.get(counter);
if (oldString.length() + word.length() <= K - 1) {
subStrings.set(counter, sj.add(oldString).add(word).toString());
} else {
counter++;
subStrings.add(counter, sj.add(word).toString());
}
} else {
subStrings.add(sj.add(word).toString());
}
}
subStrings.forEach(
v -> {
System.out.printf("[%s] and length %d\n", v, v.length());
}
);
splitCount = subStrings.size();
return splitCount;
}
public static void main(final String[] args) {
final MessageSolution messageSolution = new MessageSolution();
final String message = "SMSas5 ABC DECF HIJK1566 SMS POP SUV XMXS MSMS";
final int maxSize = 11;
System.out.println(messageSolution.solution(message, maxSize));
}

Categories