Java method to reverse every word in an array of strings - java

I'm trying to make a method that will take an array of strings and return an array with all the words in reverse order but my code is not working.
When I run it i get "[Ljava.lang.String;#74122d9c"
Test case: String[]words={"Monday","Tuesday","Wednesday"}; -->{"yadnoM","yadsueT","yadsendeW"};
public String[] reverseString(String[] words)
{
String[] t=new String[words.length];
for(int i=0;i<words.length;i++)
{
for(int j=words[i].length()-1;j>=0;j--)
{
t[i]+=words[i].substring(j,j+1);
}
}
return t;
}

When I run your code, I didn't get the same error that you posted, but I did notice that null was at the end of each reversed word.
nullyadnoM
nullyadseuT
nullyadsendeW
Which is beacuse when you create a new string array, all it's values default to null:
String[] t = new String[words.length];
The easiest way to fix it is to set it's value to an empty string, before you start adding to it:
public static String[] reverseString(String[] words)
{
String[] text = new String[words.length];
for (int i = 0; i < words.length; i++)
{
text[i] = "";
for (int j = words[i].length() - 1; j >= 0; j--)
text[i] += words[i].charAt(j);
}
return text;
}
I have tested this code, and it works perfectly fine for me.
To output the array, instead of using
System.out.println(words);
use the following:
System.out.println(Arrays.toString(words));
This will give you the output:
[yadnoM, yadseuT, yadsendeW]

You can transform your string into StringBuilder and it had reverse method. And its always better to use foreach rather than for, until there is actual need.
public String[] reverseString(String[] words) {
String[] t = new String[words.length];
for (String wordTemp : words) {
StringBuilder sb = new StringBuilder(wordTemp);
t[i] = sb.reverse().toString();
}
return t;
}
Alternate approach :-
public String[] reverseString(String[] words)
{
String[] t=new String[words.length];
for(int i=0;i<words.length;i++)
{
//added for setting elemennt as emptyString instead of null
t[i] = "";
for(int j=words[i].length()-1;j>=0;j--)
{
t[i]+=words[i].substring(j,j+1);
}
}
//using loop
for(int i=0;i<words.length;i++)
{
System.out.println(t[i]);
}
//using Arrays Method
System.out.println(Arrays.toString(t));
return t;
}

try using StringBuilder.reverse
public String[] reverseString(String[] words) {
String[] t = new String[words.length];
for (int i = 0; i < words.length; i++) {
t[i]= new StringBuilder(words[i]).reverse().toString();
}
return t;
}
Update
The fact that you are getting When I run it i get "[Ljava.lang.String;#74122d9c" is beccase you are printing the whole String array as one [Ljava.lang.String means String array. You will need to iterate over the array to print out the Strings one-by-one

public static void main(String[] args) {
String[] words = { "Monday", "Tuesday", "Wednesday" };
for (int i = 0 ; i < words.length ; i++) {
words[i] = Reverse(words[i]);
}
for (int i = 0 ; i < words.length ; i++) {
System.out.println(words[i]);
}
}
private static String Reverse(String str) {
StringBuilder result = new StringBuilder();
StringTokenizer st = new StringTokenizer(str, "");
while (st.hasMoreTokens()) {
StringBuilder thisToken = new StringBuilder(st.nextToken());
result.append(thisToken.reverse() + " ");
}
return result.toString();
}
Output
yadnoM
yadseuT
yadsendeW
Also you can use org.apache.commons.lang3.StringUtils;, just to reduce your effort/shorten the code
private static String Reverse(String str) {
return StringUtils.reverse(str);
}

Below Code is working fine with the help Stringbuilder reverse function.
public class Example {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] irreverseStr = {"Monday","Tuesday","Wendesday","Thursday","Friday","Saturday","Sunday"};
String[] reverseStr = new Example().getReverseArray(irreverseStr);
for(int j = 0; j < reverseStr.length; j++){
System.out.println(reverseStr[j]);
}
}
public String[] getReverseArray(String[] str){
String [] reversestr = new String[str.length];
for(int i=0;i<reversestr.length;i++){
reversestr[i] = new StringBuilder(str[i]).reverse().toString();
}
return reversestr;
}
}

public static String[] reverseString(String[] words) {
String[] t = new String[words.length];
for (int i = 0; i < words.length; i++) {
t[i]=new StringBuffer(words[i]).reverse().toString();
}
return t;
}
try StringBuffer's reverse method

java 8+
public String[] reverseStringArray(String[] test){
String[] result = Arrays.stream(test).map(item -> {
List<String> list = Arrays.asList(item.split(""));
Collections.reverse(list);
return String.join("", list);
}).collect(Collectors.toList()).toArray(new String[0]);
return result;
}

Related

How do I reverse every string in a string array?

public static void reverse(String[] array){
String reverse = "";
for(int i=0;i<array.length;i++){
for(int j = array[i].length() - 1; j >= 0; i--)
{
reverse = reverse + array[i].charAt(i);
}
}
}
Using this method I am trying to reverse every single string in the string array but it just throws an exception. The array's length and elements are being inputed with scanner.
public static String[] arrayStringCreation(String[] array){
boolean isArrayInputStillGoing = true;
while (isArrayInputStillGoing){
System.out.println();
System.out.println("Input the size of the array");
int sizeOfArray = scanner.nextInt();
if (sizeOfArray <= 0){
System.err.println("Size can't be less than 1");
continue;
}
array = new String[sizeOfArray+1];
System.out.println("Input words less than 20 symbols");
for(int i=0;i<sizeOfArray+1;i++){
array[i] = scanner.nextLine();
if (array[i].length()>20){
System.err.println("Try again with a word with less than 20 symbols");
i--;
}
}
isArrayInputStillGoing=false;
}
return array;
}
StringBuilder::reverse
Simply iterate the array, and replace each entry with its reverse. You can use a StringBuilder to reverse a String, calling StringBuilder.reverse.
Like,
public static void reverse(String[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = new StringBuilder(array[i]).reverse().toString();
}
}
And then to test it
public static void main(String[] args) {
String arr[] = { "abc", "def" };
reverse(arr);
System.out.println(Arrays.toString(arr));
}
See this code run live at IdeOne.com.
[cba, fed]
Stream
The Answer by Elliott Frisch is correct and robust, and should be accepted.
In addition, for fun, here is a version of that code using streams rather than the conventional for loop. I am not claiming this is better.
I do not know of a way for a stream of an array to affect that array. So instead here I make and return a fresh array.
public static String[] reverse( String[] array ) {
Objects.requireNonNull( array , "Received null argument where an array of `String` was expected. Message # b5c03336-4b9e-4735-a054-16e43aac059e.") ;
Stream< String > stream = Arrays.stream( array ) ;
String[] result =
stream
.map( ( String s ) -> new StringBuilder( s ).reverse().toString() )
.toArray(String[]::new)
;
return result ;
}
Usage.
String arr[] = { "abc" , "def" , "mask😷" } ;
String arr2[] = Ideone.reverse( arr ) ;
System.out.println( Arrays.toString( arr ) ) ;
System.out.println( Arrays.toString( arr2 ) ) ;
See that code run live at IdeOne.com.
[abc, def, mask😷]
[cba, fed, 😷ksam]
You can use StringUtils.reverse of org.apache.commons.lang3 from the Apace Commons project. That method handles null.
public static void reverse(String[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = StringUtils.reverse(array[i]);
}
}
You didn't update the array with the reverse string and decrement j in the inner loop
public static void reverse(String[] array) {
String reverse;
for (int i = 0; i < array.length; i++) {
reverse = "";
for (int j = array[i].length() - 1; j >= 0; j--) {
reverse += array[i].charAt(j);
}
array[i] = reverse;
}
}
, main
public static void main(String[] args) {
String arr[] = { "head", "body", "hand" };
reverse(arr);
System.out.println(Arrays.toString(arr));
}
, output
[daeh, ydob, dnah]
Here is another option. It will work in most versions of Java. Instead of returning a new Array, it simply modifies the one that is passed.
public class ReverseStringsInArray {
public static void main(String[] args) {
String [] strArr = {"alpha", "beta","gamma","delta"};
reversed(strArr);
for (String v : strArr) {
System.out.println(v);
}
}
public static void reversed(String[] arr) {
int k = 0;
for (String v : arr) {
int[] s = v.codePoints().toArray();
int len = v.length();
// swap the outer characters as the pointer moves
// towards the middle
for (int i = 0; i < len >> 1; i++) {
int cp = s[i];
s[i] = s[len - i - 1];
s[len - i - 1] = cp;
}
arr[k++] = new String(s,0,s.length);
}
}
}

How do I count each word in a file using Java

Im trying to write a program with three instance methods, but I cant seem to get it right. My method wordCount returns the number of lines in the file. Not the number of words as its supposed to.
Im just lost in the method mostFrequentWords..
Hope someone can help me out
package opgaver;
import java.util.*;
import java.io.*;
public class TextAnalysis14 {
Scanner file;
int CountWords = 0;
boolean Contains = true;
String[] words;
String[] MFwords;
public TextAnalysis14(String sourceFileName, int maxNoOfWords) {
String wordline;
words = new String[maxNoOfWords];
String[] line;
try {
file = new Scanner(new File(sourceFileName));
} catch (FileNotFoundException e) {
file = new Scanner("");
}
while (file.hasNext()) {
wordline = file.next();
line = wordline.split("[^a-zA -Z]+");
for (int i = 0; i < line.length; i++) {
if (!line[i].equals(" ")) {
words[CountWords] = line[i];
CountWords++;
}
}
}
if (words[CountWords] == (null)) {
for (int i = CountWords; i < maxNoOfWords; i++) {
words[i] = ("empty");
}
}
}
public int wordCount() {
return CountWords;
}
public boolean contains(String word) {
for (int i = 0; i < words.length; i++) {
if (words[i].contains(word)) {
return Contains;
}
}
return false;
}
public String[] mostFrequentWords() {
Arrays.sort(words);
return MFwords;
}
}
Because of my noob status I cannot make a comment but it looks like you have a space in your regex between A and -Z.
try with this.
public static void main(String[] args) {
String str = "this is a space String"; // read all lines in a file
String[] splited = str.split(" ");
List<String> list = new ArrayList<String>();
for(int i = 0;i < splited.length; i++){
if(splited[i].length() > 0){
list.add(splited[i]);
}
}
System.out.println(list.size());
}
by calling wordline = file.next(); you are not reading lines.
In TextAnalysis14 change your condition to file.hasNextLine() and read lines with file.nextLine()
while (file.hasNextLine()) {
wordline = file.nextLine();
....
}
You can try something like that using Java 8:
Stream<String> lines = Files.lines(Paths.get("c:/", "file.txt"));
in wordCount = lines.mapToInt(s -> s.split(' ').length()).sum();
This function just cound a words count in file.

Generating String Tokens in 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/

How can you convert a 2 dimensional array into a 1 dimensional array in Java

I would like to know how to convert a 2 dimensional array into a 1 dimensional array. I have come up with some code but it doesn't exactly seem to work. Can someone please help me? Thanks.
public class TESTER1 {
/**
* #param args
*/
static String[][] data = new String[][] {{"Dum","Dumer","Dumbest"}};
public static void main(String[] args) {
convertData(data);
}
public static void convertData(String[][]data) {
String[] toReturn = new String[data.length];
for(int i = 0;i<data.length;i++) {
for(int j = 0;j<3;j++){
toReturn[i] = data[i][j];
}
}
for(String s:toReturn) {
System.out.println(s);
}
}
}
[edit]Thank you very much. Is it possible to convert each row in the String[][] into
a index in a String[] for example if we convert the String[][] (above code), then when
i print out array[0] it should print out dum,dummer,dumbest [edit]
public static String[] flatten(String[][] data) {
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < data.length; i++) {
for(int j = 0; j < data[i].length; j++){
list.add(data[i][j]);
}
}
return list.toArray(new String[0]);
}
Or add whole rows at one time:
for(int i = 0; i < data.length; i++) {
list.addAll( Arrays.asList(data[i]) );
}
Edit:
From comments on my answer it seems like this is what the OP wanted (i.e. converting each row of 2d array to some string representation of it):
public static String[] rowsToString(String[][] data) {
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < data.length; i++) {
String row = Arrays.toString(data[i]);
list.add( row.substring(1, row.length()-1) );
}
return list.toArray(new String[0]);
}
The length of the 1-dimensional array must be the sums of the lengths of all rows in the 2-dimensional array. Of course, Java doesn't really have "true" 2-dimensional arrays, but arrays of arrays. This code works, and is wrapped in a simple demo program.
public class ArrayFlattening {
public static final String[][] STRINGS2 = {
{"my", "dog", "has", "fleas"},
{"how", "now", "brown", "cow"},
{"short", "row"},
{"this", "is", "a", "final", "row", "in", "this", "test"},
};
public static String[] flatten(String[][] a2) {
String[] result = new String[totalSize(a2)];
int index = 0;
for (String[] a1 : a2) {
for (String s : a1) {
result[index++] = s;
}
}
return result;
}
public static int totalSize(String[][] a2) {
int result = 0;
for (String[] a1 : a2) {
result += a1.length;
}
return result;
}
public static void main(String[] args) {
System.out.println("" + STRINGS2.length + " rows");
for (String[] strings1 : STRINGS2) {
System.out.println("" + strings1.length + " strings");
for (String s : strings1) {
System.out.print("\t" + s);
}
System.out.println();
}
String[] strings1 = flatten(STRINGS2);
System.out.println(strings1.length + " strings");
for (String s : strings1) {
System.out.print("\t" + s);
}
System.out.println();
}
}
A cleaner version:
public static String[] flatten(String[][] data) {
List<String> toReturn = new ArrayList<String>();
for (String[] sublist : Arrays.asList(data)) {
for (String elem : sublist) {
toReturn.add(elem);
}
}
return toReturn.toArray(new String[0]);
}
Flatten did become much easier in Java 8 with the stream API. The function can be expressed as:
private static String[] flatten(String[][] data) {
return Stream.of(data).flatMap(Stream::of).toArray(String[]::new);
}

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