How can I get the String and the int values from a String like this : "a:10,b:15,c:20,d:30"
String mixedString = "a:10,b:15,c:20,d:30";
String requiredArray1[] = [a,b,c,d];
int requiredArray2[] = [10,15,20,20];
You can loop your String and test your String one by one:
First
You need to split your String to :
String myString = "a:10,b:15,c:20,d:30";
//split the String to get only the Strings and int in your case you need to split with , and :
String mixedString[] = myString.split(":|\\,");
Second
Test If the String is Integer then return true and insert it to the array of Integers, else Insert it to the array of Strings:
public static boolean test(String s){
try{
Integer i = Integer.parseInt(s);
return true;
}catch(Exception e){
return false;
}
}
Here how your program should look like:
public static void main(String[] args) {
String myString = "a:10,b:15,c:20,d:30";
String mixedString[] = myString.split(":|\\,");
String requiredArray1[] = new String[mixedString.length];
int requiredArray2[] = new int[mixedString.length];
int s = 0;
int n = 0;
for (int i = 0; i < mixedString.length; i++) {
if (!test(mixedString[i])) {
requiredArray1[s] = mixedString[i];
s++;
} else {
requiredArray2[n] = Integer.parseInt(mixedString[i]);
n++;
}
}
}
public static boolean test(String s) {
try {
Integer i = Integer.parseInt(s);
return true;
} catch (Exception e) {
return false;
}
}
If your mixed String is as you show in your post where every alpha character is always followed by a colon delimiter (:) and then a string representation of a numerical value, you really don't need an additional method to test for whether or not a numerical value is there. You simply know its there just as you know there is a alpha value there as well...or...maybe you don't and maybe you should test for the alpha as well. You don't specify either way within your post what different possibilities might exist within the mixed string. Therefore, we can assume that:
Every alpha section is delimited with a colon (:) and then followed by a string representation of a numerical value which so far does indeed appear to be Integer. This is then followed by a comma (,) delimiter and yet another colon delimited alpha/numerical pair.
String mixedString = "a:10,b:15,c:20,d:30";
System.out.println("Original String: \"" + mixedString + "\"\n");
String[] mStringArray= mixedString.split(",");
String[] alphaArray = new String[mStringArray.length];
int[] numericArray = new int[mStringArray.length];
for (int i = 0; i < mStringArray.length; i++) {
String[] tmp = mStringArray[i].split(":");
alphaArray[i] = tmp[0];
numericArray[i] = Integer.parseInt(tmp[1]);
}
// Display contents of the two Arrays
System.out.println("Elements From Alpha Array");
for (int i = 0; i < alphaArray.length; i++) {
System.out.println(alphaArray[i]);
}
System.out.println("\nElements From Numeric Array");
for (int i = 0; i < numericArray.length; i++) {
System.out.println(numericArray[i]);
}
public static void main(String[] args) {
String myString = "a:10,b:15,c:20,d:30";
// extract all numbers (All elements are numbers so you can convert it to int easily )
String[] requiredArray1 = extractAllAccordingToRegex("\\d+", myString);
// extract all characters
String[] requiredArray2 = extractAllAccordingToRegex("[a-zA-Z]+",myString);
}
static String[] extractAllAccordingToRegex(String inputRegex, String input) {
List<String> extractedItems = new ArrayList<String>();
Pattern reg = Pattern.compile(inputRegex);
Matcher m = reg.matcher(input);
while (m.find()) {
extractedItems.add(m.group());
}
return extractedItems.toArray(new String[1]);
}
Related
This post is an update to this one : get specific character in a string with regex and remove unused zero
In the first place, i wanted to remove with an regular expression the unused zero in the last match.
I found that the regular expression is a bit overkill for what i need.
Here is what i would like now,
I would like to use split() method
to get from this :
String myString = "2020-LI50532-3329-00100"
this :
String data1 = "2020"
String data2 = "LI50532"
String data3 = "3329"
String data4 = "00100"
So then i can remove from the LAST data the unused Zero
to convert "00100" in "100"
And then concatenate all the data to get this
"2020-LI50532-3329-100"
Im not familiar with the split method, if anyone can enlight me about this ^^
You can use substring method to get rid of the leading zeros...
String myString = "2020-LI50532-3329-00100";
String[] data = myString.split("-");
data[3] = data[3].substring(2);
StringBuilder sb = new StringBuilder();
sb.append(data[0] + "-" + data[1] + "-" + data[2] + "-" + data[3]);
String result = sb.toString();
System.out.println(result);
Assuming that we want to remove the leading zeroes of ONLY the last block, maybe we can:
Extract the last block
Convert it to Integer and back to String to remove leading zeroes
Replace the last block with the String obtained in above step
Something like this:
public String removeLeadingZeroesFromLastBlock(String text) {
int indexOfLastDelimiter = text.lastIndexOf('-');
if (indexOfLastDelimiter >= 0) {
String lastBlock = text.substring(indexOfLastDelimiter + 1);
String lastBlockWithoutLeadingZeroes = String.valueOf(Integer.valueOf(lastBlock)); // will throw exception if last block is not an int
return text.substring(0, indexOfLastDelimiter + 1).concat(lastBlockWithoutLeadingZeroes);
}
return text;
}
Solution using regex:
public class Main {
public static void main(String[] args) {
// Test
System.out.println(parse("2020-LI50532-3329-00100"));
System.out.println(parse("2020-LI50532-3329-00001"));
System.out.println(parse("2020-LI50532-03329-00100"));
System.out.println(parse("2020-LI50532-03329-00001"));
}
static String parse(String str) {
return str.replaceAll("0+(?=[1-9]\\d*$)", "");
}
}
Output:
2020-LI50532-3329-100
2020-LI50532-3329-1
2020-LI50532-03329-100
2020-LI50532-03329-1
Explanation of the regex:
One or more zeros followed by a non-zero digit which can be optionally followed by any digit(s) until the end of the string (specified by $).
Solution without using regex:
You can do it also by using Integer.parseInt which can parse a string like 00100 into 100.
public class Main {
public static void main(String[] args) {
// Test
System.out.println(parse("2020-LI50532-3329-00100"));
System.out.println(parse("2020-LI50532-3329-00001"));
System.out.println(parse("2020-LI50532-03329-00100"));
System.out.println(parse("2020-LI50532-03329-00001"));
}
static String parse(String str) {
String[] parts = str.split("-");
try {
parts[parts.length - 1] = String.valueOf(Integer.parseInt(parts[parts.length - 1]));
} catch (NumberFormatException e) {
// Do nothing
}
return String.join("-", parts);
}
}
Output:
2020-LI50532-3329-100
2020-LI50532-3329-1
2020-LI50532-03329-100
2020-LI50532-03329-1
you can convert the last string portion to integer type like below for removing unused zeros:
String myString = "2020-LI50532-3329-00100";
String[] data = myString.split("-");
data[3] = data[3].substring(2);
StringBuilder sb = new StringBuilder();
sb.append(data[0] + "-" + data[1] + "-" + data[2] + "-" + Integer.parseInt(data[3]));
String result = sb.toString();
System.out.println(result);
You should avoid String manipulation where possible and rely on existing types in the Java language. One such type is the Integer. It looks like your code consists of 4 parts - Year (Integer) - String - Integer - Integer.
So to properly validate it I would use the following code:
Scanner scan = new Scanner("2020-LI50532-3329-00100");
scan.useDelimiter("-");
Integer firstPart = scan.nextInt();
String secondPart = scan.next();
Integer thirdPart = scan.nextInt();
Integer fourthPart = scan.nextInt();
Or alternatively something like:
String str = "00100";
int num = Integer.parseInt(str);
System.out.println(num);
If you want to reconstruct your original value, you should probably use a NumberFormat to add the missing 0s.
The main points are:
Always try to reuse existing code and tools available in your language
Always try to use available types (LocalDate, Integer, Long)
Create your own types (classes) and use the expressiveness of the Object Oriented language
public class Test {
public static void main(String[] args) {
System.out.println(trimLeadingZeroesFromLastPart("2020-LI50532-03329-00100"));
}
private static String trimLeadingZeroesFromLastPart(String input) {
String delem = "-";
String result = "";
if (input != null && !input.isEmpty()) {
String[] data = input.split(delem);
StringBuilder tempStrBldr = new StringBuilder();
for (int idx = 0; idx < data.length; idx++) {
if (idx == data.length - 1) {
tempStrBldr.append(trimLeadingZeroes(data[idx]));
} else {
tempStrBldr.append(data[idx]);
}
tempStrBldr.append(delem);
}
result = tempStrBldr.substring(0, tempStrBldr.length() - 1);
}
return result;
}
private static String trimLeadingZeroes(String input) {
int idx;
for (idx = 0; idx < input.length() - 1; idx++) {
if (input.charAt(idx) != '0') {
break;
}
}
return input.substring(idx);
}
}
Output:
2020-LI50532-3329-100
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 check if a given string can be made from a given set of strings? In the set of given strings, any string can be used any number of times only these strings can't be splitted."
For e.g.,
given set of strings are:
<aaa, hh, aa, rr>
Strings to check:
rraaahh :: returns True
raahh :: returns False
aarrr :: returns True
Below I have written a function that selects any two strings from the set of strings and check if the given string can be made from the selected strings.
But how do I approach for taking more than two strings at a time where any string can be used multiple times.
static boolean isPossible(Vector<String> v, String str)
{
// Sort the given string
str = sortString(str);
// Select two strings at a time from given vector
for (int i = 0; i < v.size() - 1; i++)
{
for (int j = i + 1; j < v.size(); j++)
{
// Get the concatenated string
String temp = v.get(i) + v.get(j);
// Sort the resultant string
temp = sortString(temp);
// If the resultant string is equal
// to the given string str
if (temp.compareTo(str) == 0)
{
return true;
}
}
}
// No valid pair found
return false;
}
Simple replacement does not work, as "aaaa" always matches at first on "aaa", just leaving "a" as a rest. But you can solve it recursivly.
public static void main(String[] args) {
String input = "aaaarrrraahhaaa";
ArrayList<String> list = new ArrayList<String>() {
{
add("aaa");
add("hh");
add("aa");
add("rr");
}
};
System.out.println(isPossible(list, input));
}
static boolean isPossible(List<String> fragments, String input) {
return isOkay(fragments, input, "");
}
private static boolean isOkay(List<String> list, String input, String candidate) {
for (int i = 0; i < list.size(); i++) {
String testee = candidate + list.get(i);
if (testee.equals(input)) {
return true;
}
if (input.startsWith(testee)) {
boolean tempResult = isOkay(list, input, testee);
if (tempResult) {
return true;
}
}
testee = candidate;
}
return false;
}
Simple check if the string input contains the substrings in list. If any letter is left, it is not made up by those substrings and return false. Try this code as follows.
public static void main(String[] args) {
String input = "aarr";
ArrayList<String> list = new ArrayList<String>() {{
add("aaa");
add("hh");
add("aa");
add("rr");
}};
System.out.println(isPossible(list, input));
}
static boolean isPossible(ArrayList<String> list, String input) {
int count = 4;
for (String item : list) {
if (input.contains(item)) {
input = input.replace(item, "");
System.out.println("Debug: " + input);
}
}
if ((int) input.length() == 0) {
System.out.println("Pass: " + input.length());
return true;
} else {
System.out.println("Fail: " + input.length());
}
return false;
}
same topic : replace String with another in java
I want to replace String Replace = "SUM(NewCounter)+SUM(NewCounter2)+NewCounter3";
I have Array A = {NewCounter, NewCounter2, NewCounter3}
say I have Array B = {test, testA, testB}
I want to replace it with array A with array B in String Replace.
I try to use method ReplaceAll(A.get(index), B.get(index));
Problem is:
NewCounter2 is Read by system "NewCounter"+2
so I have result = String Replace = "SUM(test)+SUM(test2)+test3";
I try to use ' in Character NewCounter, it will be Array A = {'NewCounter', 'NewCounter2', 'NewCounter3'}
but I must change String Replace Before like this :
String Replace = "SUM('NewCounter')+SUM('NewCounter2')+'NewCounter3'";
Is there other way to me ???
I don't want to change String before...
Thanksfull,
-mazipan-
The simplest solution for simultaneous replacement is to process the strings in order of decreasing length. This will do the replacements correctly:
A = {NewCounter3, NewCounter2, NewCounter}
B = {testB, testA, test}
This technique won't work if any of the search strings could match the replacement strings, however.
Edit: For the general case, I've written this:
public static String simultaneousReplace(String subject,
String[] find, String[] replace) {
if (find.length != replace.length) throw new IllegalArgumentException(
"Strings to find and replace are not paired.");
int numPairs = find.length;
StringBuilder sb = new StringBuilder();
for (int i = 0, len = subject.length(); i < len; i++) {
int longestMatchIndex = -1;
int longestMatchLength = -1;
for (int j = 0; j < numPairs; j++) {
String find1 = find[j];
if (subject.regionMatches(false, i, find1, 0, find1.length())) {
if (find1.length() > longestMatchLength) {
longestMatchIndex = j;
longestMatchLength = find1.length();
}
}
}
if (longestMatchIndex >= 0) {
sb.append(replace[longestMatchIndex]);
i += longestMatchLength - 1;
} else {
sb.append(subject.charAt(i));
}
}
return sb.toString();
}
Example usage:
String s = "SUM(NewCounter)+SUM(NewCounter2)+NewCounter3";
s = simultaneousReplace(s,
new String[] { "NewCounter", "NewCounter2", "NewCounter3" },
new String[] { "test", "testA", "testB" }
);
System.out.println(s);
Output:
SUM(test)+SUM(testA)+testB
If SUM is just a String and not a method then you can use:
String Replace = "SUM(" + NewCounter + ")SUM(" + NewCounter2 +")" + NewCounter3;
If Sum is a method then you can use
String Replace = SUM(NewCounter) + SUM(NewCounter2) + NewCounter3;
Although for the second one you may have to cast/convert to a string by surrounding it with
().toString()
or by adding
(String)()
Apache's commons-lang StringUtils#replaceEach handles these problems elegantly.
Runnable Code :
public static void main(String [] args) {
String replace = "SUM(NewCounter)+SUM(NewCounter2)+NewCounter3";
String [] a = { "NewCounter", "NewCounter2", "NewCounter3" };
String [] b = { "test", "testA", "testB" };
System.out.println(StringUtils.replaceEach(replace, a, b));
}
Will give you
SUM(test)+SUM(test2)+test3
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.