Generating String Tokens in Java - java

I want to generate possible tokens using forward traversal in Java. For example if I have a string "This is my car". I need to generate tokens
"This is my car"
"This is my"
"This is"
"This"
"is my car"
"is my"
"is"
"my car"
"my"
"car"
What is the best way to do this? Any examples? Thanks.

Here is another solution with split and nested loops:
public static void main(String[] args) {
String original = "this is my car";
String[] singleWords = original.split(" "); // split the String to get the single words
ArrayList<String> results = new ArrayList<String>(); // a container for all the possible sentences
for (int startWord = 0; startWord < singleWords.length; startWord++) { // starWords start with 0 and increment just until they reach the last word
for (int lastWord = singleWords.length; lastWord > startWord; lastWord--) { // last words start at the end and decrement just until they reached the first word
String next = "";
for (int i = startWord; i != lastWord; i++) { // put all words in one String (starting with the startWord and ending with the lastWord)
next += singleWords[i] + " ";
}
results.add(next); // add the next result to your result list
}
}
// this is just to check the results. All your sentences are now stored in the ArrayList results
for (String string : results) {
System.out.println("" + string);
}
}
and this was my result when I tested the method:
this is my car
this is my
this is
this
is my car
is my
is
my car
my
car

Use Guava:
String yourOriginalString = "This is my car";
final Set<String> originalWords =
Sets.newLinkedHashSet(
Splitter.on(CharMatcher.WHITESPACE).trimResults().split(yourOriginalString));
final Set<Set<String>> variations = Sets.powerSet(originalWords);
for (Set<String> variation : variations) {
System.out.println(Joiner.on(' ').join(variation));
}
Output:
This
is
This is
my
This my
is my
This is my
car
This car
is car
This is car
my car
This my car
is my car
This is my car

Here is a possible way:
//Just a method that seperates your String into an array of words based on the spaces
//I'll leave that for you to figure out how to make
String[] array = getSeperatedWords(<yourword>);
List<StringBuffer> bufferArray = new ArrayList<StringBuffer>();
for(int i = 0; i < array.length; i++){
StringBuffer nowWord = array[i];
for(int j = i; j < array.length; j++{
nowWord.append(array[j]);
}
bufferArray.add(nowWord);
}
for(int i = 0; i < bufferArray.length; i++){
System.out.print(bufferArray.get(i));
}

import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String var = "This is my car";
permute(var);
}
public static void permute(String var) {
if(var.isEmpty())
return;
String[] arr = var.split(" ");
while(arr.length > 0) {
for(String str : arr) {
System.out.print(str + " ");
}
arr = (String[]) Arrays.copyOfRange(arr, 0, arr.length - 1);
System.out.println();
}
String[] original = var.split(" ");
permute(implodeArray((String[]) Arrays.copyOfRange(original, 1, original.length), " "));
}
public static String implodeArray(String[] inputArray, String glueString) {
String output = "";
if (inputArray.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append(inputArray[0]);
for (int i=1; i<inputArray.length; i++) {
sb.append(glueString);
sb.append(inputArray[i]);
}
output = sb.toString();
}
return output;
}
}
Read this book, you will be a master on recursion: http://mitpress.mit.edu/sicp/

Related

Split Word into Two and Check Existence in Comma Separated String Sequence

I have a string array for example:
new String[] = {"powerhouse", "p, pow, power, house, pose, poser"};
My goal is to split the first entry in the array in this case powerhouse into any two words and check them against the second entry, which serves as a dictionary of words.
Here's my implementation so far:
public static String[] convertWordsToArray(String input){
String[] wordArr = null;
wordArr = input.split(",");
return wordArr;
}
public static String splitEm(String[] strArr) {
String fw = strArr[0];
String sw = strArr[1];
String[] arrOne = convertWordsToArray(fw);
System.out.println(arrOne.length);
String[] dict = convertWordsToArray(sw);
System.out.println(dict.length);
for(int i = 0; i < dict.length - 1; i++) {
String mWord = fw.split(i, i + 1);
System.out.println(mWord);
}
// Edit Starts Here, tried to substring it but nothing prints in log
for(int i = 0; i < arrOne.length; i++) {
String mWord = fw.substring(0, i);
System.out.println(mWord);
}
return ""; // empty for now
}
I am stuck at the part where the first word has to be split. Should I use two loops, one for the first word and the other for the dictionary? I know that somehow the dictionary has to be converted to a list or array list to avail the .contains() method. How do I go about this? Thanks.
If anyone want the solution for PHP language, then you can use below code:
function ArrayChallenge($strArr) {
$dictWords = explode( ',', $strArr[1] );
$strLength = strlen($strArr[0]);
$output = 'not possible';
for( $i = 1; $i < $strLength; $i++ ){
$firstStr = substr($strArr[0], 0, $i);
$lastStr = substr($strArr[0], $i, $strLength);
if ( in_array( $firstStr, $dictWords ) && in_array( $lastStr, $dictWords ) ) {
$output = $firstStr . ',' . $lastStr;
break;
}
}
return $output;
}
Do you need something like this?
String s = "powerhouse";
List<String> list = new ArrayList<String>();
for(int i = 0; i < s.length(); i++){
for(int j = i+1; j <= s.length(); j++){
list.add(s.substring(i,j));
}
}
System.out.println(list);
I assume you need something like below:
Split second string at each , or even better using regex to trim
spaces before or after ,
check if each part of the splited entry fro above point is made of
only the chars contained in the first entry of your input
example
public static void main(String args[]) {
String[] test1 = {"powerhouse", "p, pow, power, house, pose, poser"};
String[] test2 = {"powerhouse", "p, xyz, power, house, pose, poser"};
System.out.println(check(test1));
System.out.println(check(test2));
}
static boolean check(String[] input){
String firstEntry = input[0];
String[] dictionary = input[1].split("\\s*,\\s*");
for(int i = 0; i < dictionary.length; i++){
if(!dictionary[i].matches("["+firstEntry+"]+")){
return false;
}
}
return true;
}
this will print true for the first case and false for the second as "xyz" is not a valid subpart/substring according to your discription
Try this :
public class Stack {
public static void main(String[] args) {
String[] str = {"powerhouse", "p, pow, power, house, pose, poser"};
String firstPart = str[0];
String secondPart = str[1];
boolean contain = isContain(firstPart, secondPart);
System.out.println(contain);
}
private static boolean isContain(String firstPart, String secondPart) {
for (int i = 0; i < firstPart.length(); i++) {
String firstWord = firstPart.substring(0, i);
String secondWord = firstPart.substring(i, firstPart.length());
List<String> strings = Arrays.asList(secondPart.trim().split("\\s*,\\s*"));
if (strings.contains(firstWord) && strings.contains(secondWord)) return true; if you want to check both words use this
//if (strings.contains(firstWord) || strings.contains(secondWord)) return true; if you want to check any(one) word from two words use this
}
return false;
}
}

How to split a String into an Array if a .contains() condition is met?

I'm doing a hackerrank medium challenge for a password cracker. I want to be able to check if a given string, attempt, contains all the words in pass. pass is an array of passwords and attempt is a concatenation of random entries in pass. If attempt contains ONLY words that are found as entries in pass, then it is deemed a good password and the words from the input of attempt, limited with spaces, is printed.
Sample Input
3 //3 attempts
6 //6 words for attempt 1
because can do must we what //pass[]
wedowhatwemustbecausewecan //attempt
2 //...
hello planet
helloworld
3
ab abcd cd
abcd
Expected Output
we do what we must because we can
WRONG PASSWORD //Because planet is not in pass[]
ab cd
Code
public class Solution {
static String passwordCracker(String[] pass, String attempt) {
int arrayLength=pass.length;
int accuracy=0;
String trips_array[] = new String[pass.length];
String [] newWord = new String[20];
for (int i=0; i<pass.length;i++)
{
// int j=0;
String[] arr = pass[i].split(" ");
//-------------------------------
if (attempt.contains(pass[i]))
{
accuracy++;
newWord[i] = pass[i];
trips_array[i] = attempt.split(" ");
}
//------------------------------
}
StringBuilder sb = new StringBuilder();
for (String words : trips_array) {
sb.append(words);
}
for (int i=0; i<pass.length;i++)
{
if (accuracy==pass.length)
return sb.toString() + " ";
else
return "WRONG PASSWORD";
}
return "test";
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int n = in.nextInt();
String[] pass = new String[n];
for(int pass_i = 0; pass_i < n; pass_i++){
pass[pass_i] = in.next();
}
String attempt = in.next();
String result = passwordCracker(pass, attempt);
System.out.println(result);
}
in.close();
}
}
The part in focus is the part in the //----------------- comment section. Basically, my goal is to see if the attempt contains the correct entries in pass, and if so, save that substring of the attempt (or similarly, the entry in pass) to a new array which can be printed in the correct order. If you check the expected output above, you'll see that the output is the same as attempt except with spaces.
Essentially, I would need to find the breaks in the words of attempt and print that if it fulfills the above requirements (first paragraph).
See this for more details
https://www.hackerrank.com/challenges/password-cracker/problem
If it helps you
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int testNumb = Integer.parseInt(reader.readLine());
List<String> passList = new ArrayList<>();
List<String> attList = new ArrayList<>();
for (int i = 0; i < testNumb; i++) {
reader.readLine();
passList.add(reader.readLine());
attList.add(reader.readLine());
}
reader.close();
for (int i = 0; i < testNumb; i++) {
String s1 = passList.get(i);
String s2 = attList.get(i);
StringBuilder sb = new StringBuilder();
String[] s1Arr = s1.split(" ");
while (s2.length() > 0) {
int s2Lenght = s2.length();
for (String s : s1Arr) {
if (s2.startsWith(s)) {
sb.append(s + " ");
s2 = s2.substring(s.length());
}
}
if (s2.length() == s2Lenght) {
sb = new StringBuilder("wrong pass");
break;
}
}
System.out.println(sb.toString());
}
Your for loop looks too complicated, here is how I would approach that part.
boolean isAllWords = true;
int checksum = 0;
for (int j = 0; j < pass.length; j++) {
if (!attempt.contains(pass[j]) {
isAllWords = true;
break;
}
checksum += pass[j].length;
}
if (isAllWords && checksum == attempt.length) {
//This means attempt contains all words in pass array and nothing more
//... handle successful attempt
} else {
//... handle bad attempt
}

I need to randomly remove half of the words in a string in java

Ok so I'm working on this code to blend humanities and STEM. I know very basic java code and so I'm currently trying to stick to String methods. I know using arrays may be easier but I'm not well learned in how to use them. So so far I've made code that counts the words in the string in order to determine how many words to remove (half of them). Next I need to figure out a way to randomly remove half of the words and return a new string, possibly with spaces replacing the removed letters.
Here is my code so far:
public class wordcount
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
int wordCount = wordArray.length;
System.out.println(str1 + "");
System.out.println("Word count is = " + wordCount);
int wordCount2 = wordCount/2;
}
}
I copied the array to an arrayList to then iterate through the list and delete random elements. I hope this is the type of answer you are looking for.
public static void main(String[] args) {
String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(wordArray));
int wordCount = wordList.size();
int halfWordCount = wordCount/2;
int tracker = 0; //counter for iterations in while loop
Random random = new Random();
while(tracker < halfWordCount){
int randomIndex = random.nextInt(wordList.size());
wordList.remove(randomIndex);
tracker++;
}
System.out.println(wordList.toString());
}
import java.util.Arrays;
import java.util.* ;
public class wordcount
{
public ArrayList<Integer> test(Integer[] array)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
public ArrayList<String> testS(String[] array)
{
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
public static void main (String[] args)
{
System.out.println("Removing random words in a Poem Program");
String str1 = "Sample Poem by Noah Eli Gordon: Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
int wordCount = wordArray.length;
System.out.println(str1 + "");
//System.out.println("Word count is = " + wordCount);
//System.out.println(wordArray);
//String[] ret = wordArray;
//for(String str : ret)
// System.out.print(str);
int wordCount2 = wordCount/2;
Integer[] myIntArray = new Integer[wordCount];
//for(int i = 0; i<wordCount;i++)
// myIntArray[i] = i;
//for(int str : myIntArray)
//System.out.print(str);
wordcount w = new wordcount();
String[] wordArray2 = new String[wordCount2];
for(int i = 0; i <= wordCount2; i++)
{
int rand = (int)(Math.random()*(myIntArray.length-1));
ArrayList<Integer> list = w.test(myIntArray);
list.remove(rand);
myIntArray = list.toArray(myIntArray);
ArrayList<String> listS = w.testS(wordArray);
listS.remove(rand);
wordArray2 = listS.toArray(wordArray);
}
List<String> list = new ArrayList<String>();
for(String s : wordArray2)
{
if(s != null && s.length() > 0)
{
list.add(s);
}
}
wordArray2 = list.toArray(new String[list.size()]);
//for(int str : myIntArray)
//System.out.println(str);
System.out.println();
String[] ret2 = wordArray2;
for(String str : ret2)
System.out.print(str + " ");
}
}

Counting words from array in a string

I have an array of string say
A=["hello", "you"]
I have a string, say
s="hello, hello you are so wonderful"
I need to count the number of occurrence of strings from A in s.
In this case, the number of occurrences is 3 (2 "hello", 1 "you").
How to do this effectively? (A might contains lots of words, and s might be long in practice)
Try:
Map<String, Integer> wordCount = new HashMap<>();
for(String a : dictionnary) {
wordCount.put(a, 0);
}
for(String s : text.split("\\s+")) {
Integer count = wordCount.get(s);
if(count != null) {
wordCount.put(s, count + 1);
}
}
public void countMatches() {
String[] A = {"hello", "you"};
String s = "hello, hello you are so wonderful";
String patternString = "(" + StringUtils.join(A, "|") + ")";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(s);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}
Note that StringUtils is from apache commons. If you don't want to include and additional jar you can just construct that string using a for loop.
HashSet<String> searchWords = new HashSet<String>();
for(String a : dictionary) {
searchWords.add(a);
}
int count = 0;
for(String s : input.split("[ ,]")) {
if(searchWords.contains(s)) {
count++;
}
}
int count =0;
for(int i=0;i<A.length;i++)
{
count = count + s.split(A[i],-1).length - 1;
}
Working Ideone : http://ideone.com/Z9K3JX
This is fully working method with output :)
public static void main(String[] args) {
String[] A={"hello", "you"};
String s= "hello, hello you are so wonderful";
int[] count = new int[A.length];
for (int i = 0; i < A.length; i++) {
count[i] = (s.length() - s.replaceAll(A[i], "").length())/A[i].length();
}
for (int i = 0; i < count.length; i++) {
System.out.println(A[i] + ": " + count[i]);
}
}
What does this line do?
count[i] = (s.length() - s.replaceAll(A[i], "").length())/A[i].length();
This part s.replaceAll(A[i], "") changes all "hello" to empty "" string in the text.
So I take the length of everything s.length() I substract from it the length of same string without that word s.replaceAll(A[i], "").length() and I divide it by the length of that word /A[i].length()
Sample output for this example :
hello: 2
you: 1
You can use the String Tokenizer
Do something like this:
A = ["hello", "you"];
s = "hello, hello you are so wonderful";
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreElements()) {
for (String i: A) {
if(st.nextToken() == i){
//You can keep going from here
}
}
}
This is what I came up with:
It doesn't create any new objects. It uses String.indexOf(String, int), keeps track of the current index, and increments the occurance-count.
public class SearchWordCount {
public static final void main(String[] ignored) {
String[] searchWords = {"hello", "you"};
String input = "hello, hello you are so wonderful";
for(int i = 0; i < searchWords.length; i++) {
String searchWord = searchWords[i];
System.out.print(searchWord + ": ");
int foundCount = 0;
int currIdx = 0;
while(currIdx != -1) {
currIdx = input.indexOf(searchWord, currIdx);
if(currIdx != -1) {
foundCount++;
currIdx += searchWord.length();
} else {
currIdx = -1;
}
}
System.out.println(foundCount);
}
}
}
Output:
hello: 2
you: 1

I want to split string without using split function?

I want to split string without using split . can anybody solve my problem I am tried but
I cannot find the exact logic.
Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.
You will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.
I'm going to assume that this is homework, so I will only give snippets as hints:
Finding indices of all occurrences of a given substring
Here's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:
String text = "012ab567ab0123ab";
// finding all occurrences forward: Method #1
for (int i = text.indexOf("ab"); i != -1; i = text.indexOf("ab", i+1)) {
System.out.println(i);
} // prints "3", "8", "14"
// finding all occurrences forward: Method #2
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
System.out.println(i);
} // prints "3", "8", "14"
String API links
int indexOf(String, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.
Related questions
Searching for one string in another string
Extracting substrings at given indices out of a string
This snippet extracts substring at given indices out of a string and puts them into a List<String>:
String text = "0123456789abcdefghij";
List<String> parts = new ArrayList<String>();
parts.add(text.substring(0, 5));
parts.add(text.substring(3, 7));
parts.add(text.substring(9, 13));
parts.add(text.substring(18, 20));
System.out.println(parts); // prints "[01234, 3456, 9abc, ij]"
String[] partsArray = parts.toArray(new String[0]);
Some key ideas:
Effective Java 2nd Edition, Item 25: Prefer lists to arrays
Works especially nicely if you don't know how many parts there'll be in advance
String API links
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Related questions
Fill array with List data
You do now that most of the java standard libraries are open source
In this case you can start here
Use String tokenizer to split strings in Java without split:
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
This is the right answer
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
/**
* My method split without javas split.
* Return array with words after mySplit from two texts;
* Uses trim.
*/
public class NoJavaSplit {
public static void main(String[] args) {
String text1 = "Some text for example ";
String text2 = " Second sentences ";
System.out.println(Arrays.toString(mySplit(text1, text2)));
}
private static String [] mySplit(String text1, String text2) {
text1 = text1.trim() + " " + text2.trim() + " ";
char n = ' ';
int massValue = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == n) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text1.length(); j++) {
if (text1.charAt(j) == n) {
splitArray[i] = text1.substring(0, j);
text1 = text1.substring(j + 1, text1.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
}
you can try, the way i did `{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for(int i = 0; i <str.length();i++) {
if(str.charAt(i)==' ') { // whenever it found space it'll create separate words from string
System.out.println();
continue;
}
System.out.print(str.charAt(i));
}
sc.close();
}`
The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?
The way to go is to define the function you need first. In this case, it would probably be:
String[] split(String s, String separator)
The return type doesn't have to be an array. It can also be a list:
List<String> split(String s, String separator)
The code would then be roughly as follows:
start at the beginning
find the next occurence of the delimiter
the substring between the end of the previous delimiter and the start of the current delimiter is added to the result
continue with step 2 until you have reached the end of the string
There are many fine points that you need to consider:
What happens if the string starts or ends with the delimiter?
What if multiple delimiters appear next to each other?
What should be the result of splitting the empty string? (1 empty field or 0 fields)
You can do it using Java standard libraries.
Say the delimiter is : and
String s = "Harry:Potter"
int a = s.find(delimiter);
and then add
s.substring(start, a)
to a new String array.
Keep doing this till your start < string length
Should be enough I guess.
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class WithoutSpit_method {
public static void main(String arg[])
{
char[]str;
String s="Computer_software_developer_gautam";
String s1[];
for(int i=0;i<s.length()-1;)
{
int lengh=s.indexOf("_",i);
if(lengh==-1)
{
lengh=s.length();
}
System.out.print(" "+s.substring(i,lengh));
i=lengh+1;
}
}
}
Result: Computer software developer gautam
Here is my way of doing with Scanner;
import java.util.Scanner;
public class spilt {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String to be Spilted : ");
String st = input.nextLine();
Scanner str = new Scanner(st);
while (str.hasNext())
{
System.out.println(str.next());
}
}
}
Hope it Helps!!!!!
public class StringWitoutPre {
public static void main(String[] args) {
String str = "md taufique reja";
int len = str.length();
char ch[] = str.toCharArray();
String tmp = " ";
boolean flag = false;
for (int i = 0; i < str.length(); i++) {
if (ch[i] != ' ') {
tmp = tmp + ch[i];
flag = false;
} else {
flag = true;
}
if (flag || i == len - 1) {
System.out.println(tmp);
tmp = " ";
}
}
}
}
In Java8 we can use Pattern and get the things done in more easy way. Here is the code.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
static void splitString(String s, int index) {
char[] firstPart = new char[index];
char[] secondPart = new char[s.length() - index];
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (i < index) {
firstPart[i] = s.charAt(i);
} else {
secondPart[j] = s.charAt(i);
if (j < s.length()-index) {
j++;
}
}
}
System.out.println(firstPart);
System.out.println(secondPart);
}
import java.util.Scanner;
public class Split {
static Scanner in = new Scanner(System.in);
static void printArray(String[] array){
for (int i = 0; i < array.length; i++) {
if(i!=array.length-1)
System.out.print(array[i]+",");
else
System.out.println(array[i]);
}
}
static String delimeterTrim(String str){
char ch = str.charAt(str.length()-1);
if(ch=='.'||ch=='!'||ch==';'){
str = str.substring(0,str.length()-1);
}
return str;
}
private static String [] mySplit(String text, char reg, boolean delimiterTrim) {
if(delimiterTrim){
text = delimeterTrim(text);
}
text = text.trim() + " ";
int massValue = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reg) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text.length(); j++) {
if (text.charAt(j) == reg) {
splitArray[i] = text.substring(0, j);
text = text.substring(j + 1, text.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
public static void main(String[] args) {
System.out.println("Enter the sentence :");
String text = in.nextLine();
//System.out.println("Enter the regex character :");
//char regex = in.next().charAt(0);
System.out.println("Do you want to trim the delimeter ?");
String delch = in.next();
boolean ch = false;
if(delch.equalsIgnoreCase("yes")){
ch = true;
}
System.out.println("Output String array is : ");
printArray(mySplit(text,' ',ch));
}
}
Split a string without using split()
static String[] splitAString(String abc, char splitWith){
char[] ch=abc.toCharArray();
String temp="";
int j=0,length=0,size=0;
for(int i=0;i<abc.length();i++){
if(splitWith==abc.charAt(i)){
size++;
}
}
String[] arr=new String[size+1];
for(int i=0;i<ch.length;i++){
if(length>j){
j++;
temp="";
}
if(splitWith==ch[i]){
length++;
}else{
temp +=Character.toString(ch[i]);
}
arr[j]=temp;
}
return arr;
}
public static void main(String[] args) {
String[] arr=splitAString("abc-efg-ijk", '-');
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
You cant split with out using split(). Your only other option is to get the strings char indexes and and get sub strings.

Categories

Resources