Create array with reversed words from user string - java

I am creating a program in which a user enters a string of words (Ex: I love you), and the program returns an array of the words in the string spelled backwards (Ex: I evol ouy). However, I cannot get my code to properly compile, and tried debugging, but cannot see where the problem is.
I tried to look for similar problems here on Slack, but the problems are found were concerned with rearranging words from a string, (ex: you I love), and I cannot find a problem similar to mine, involving turning string into an Array and then manipulating the array.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
char[] entryToChar = userEntry.toCharArray();
System.out.println(Arrays.toString(entryToChar));
String[] splitInput = userEntry.split(" ");
String reverseWord = "";
int temp;
String[] reverseString = new String[splitInput.length];
for (int i = 0; i < splitInput.length; i++)
{
String word = splitInput[i];
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
for (int k = 0; k < splitInput.length; k++) {
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
}
} System.out.println("Your sttring with words spelled backwards is " + reverseWord[j]);
I am avoiding using the 'StringBuilder' method as I have not yet studied it, and trying to see if I can get the new string using swapping, as in the code below:
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;

import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String word, reverseWord;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
userEntry: I love you
String[] splitInput = userEntry.split(" ");
splitInput: [I, love, you]
for (int i = 0; i < splitInput.length; i++)
{
word = splitInput[i];
reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
splitInput[i] = reverseWord;
}
splitInput: [I, evol, uoy]
System.out.println("Your string with words spelled backwards is: " + String.join(" ", splitInput));
}
}
Your string with words spelled backwards is: I evol uoy

Your code is not getting compiled because tmp variable is declared as int while splitInput[i] is String.
The other problem is variable j is outside its block scope from where you are trying to access.
Make your logic clear before writing code to achieve correct result.

A good Java programmer should know which tools exist in the language and make use of them in her/his design appropriately. I would suggest to use the class StringBuilder, which has a method for reversing the string. Your program could look like this:
while in.hasNext() {
StringBuilder sb = in.next();
sb.reverse();
System.out.println(sb.toString());
}
If you want to write the reverse function yourself for practice then you can simply define a method that takes a string and returns a reversed string and call that method in place of sb.reverse().
Please know that String in Java is an immutable object. You cannot modify it directly. You can have modified copies returned.
StringBuilder on the other hand allows the programmer to modify the object directly as you can see in the code above.

You need to split original string into an array and then reverse each one and insert into the new array, here you can use StringBuilder as good practice.
class Testarray{
public static void main(String args[]){
String str = "I am Engineer";
String[] spArray = str.split(" ");
String farr[] = new String[spArray.length];
for(int i=0;i<spArray.length;i++){
String split = spArray[i];
farr[i]=reverseString(split);
}
for(int i=0;i<farr.length;i++){
System.out.println(farr[i]);
}
}
public static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}

There are a few things going on here, and I think in some places you're mixing up between strings and arrays.
Let's try to break this problem down into smaller problems.
First, we need to reverse a single word. Your first inner loop (the one that uses j) does that, so let's extract it into its own method:
public static String reverseWord(String word) {
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord + word.charAt(j);
}
return reverseWord;
}
Although, you should note that concatenating strings like that in a loop isn't great for performance, and using a StringBuilder would probably be faster (although with such a small application, it probably won't be noticeable):
public static String reverseWord(String word) {
StringBuilder reverseWord = new StringBuilder(word.length());
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord.append(word.charAt(j));
}
return reverseWord.toString();
}
Once you have that, you can split the input string (like you did), revere each word, and join them back together:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");
for (int i = 0; i < splitInput.length; i++) {
splitInput[i] = reverseWord(splitInput[i]);
}
System.out.println("Your sttring with words spelled backwards is " +
String.join(" ", splitInput));

All you need is to split your original sentence into separate words and use StringBuilder.reverse() to get words in reverse:
public static void main(String... args) {
String str = getSentenceFromConsole();
System.out.println("Your string with words spelled backwards is '" + reversLettersInWords(str) + '\'');
}
private static String getSentenceFromConsole() {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter a string to see it in reverse: ");
return scan.nextLine();
}
}
private static String reversLettersInWords(String str) {
return Arrays.stream(str.split("\\s+"))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
}

i try with your code
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < splitInput.length; i++) {
String word = splitInput[i];
for (int j = word.length() - 1; j >= 0; j--) {
sb.append(word.charAt(j));
}
sb.append(" ");
}
System.out.println("Your sttring with words spelled backwards is " + sb.toString());
here i remove all access line of code....

String input = "i love you";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1 = input1.reverse();
System.out.println(input1);
You can use this implementation to try to reverse the string elements in the array.

Related

How can I make a java program that takes an input of words, finds certain words, replaces them and then prints out everything again?

I am not sure what to do, I have found all this online and I am trying to change it to do what I explained above but I am stuck. Basically what I want to do is copy and paste an essay into the code somewhere, the have it look through the essay for any words i tell it to look for, and if it finds them then to replace it with the word or words I want it to.
/**
*
import java.util.Arrays;
public class Main {
public static String[] wordList(String line){
return line.split(" ");
}
public static void main(String args[]) {
String words = "test words tesing";
String[] arr = wordList(words);
for(words i=0; i<words.length; i++)
for (String s: arr)
System.out.println(s);
}
}
*/
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main ( String args[] ){
String[] sEnterWord = getSortedWordArr();
showWordlist(sEnterWord);
String sWordToChange = getInputFromKeyboard("Which word would you like to change? ");
System.out.println("You have chosen to change the word : " + sWordToChange);
changeWordInArray(sWordToChange, sEnterWord);
Arrays.sort(sEnterWord);
showWordlist(sEnterWord);
}
private static String[] getSortedWordArr(){
String line = getInputFromKeyboard("How many words are you going to enter? ");
int length = Integer.valueOf(line);
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
sEnterWord[nCtr] = getInputFromKeyboard("Enter word " + (nCtr+1) + ":");
}
Arrays.sort(sEnterWord);
return sEnterWord;
}
private static String getInputFromKeyboard(String prompt){
System.out.print(prompt);
Scanner s = new Scanner(System.in);
String input = s.nextLine();
return input;
}
private static void showWordlist(String[] words){
System.out.println("Your words are: ");
for (String w : words){
System.out.println(w);
}
}
private static void changeWordInArray(String word, String[] array){
String newWord = getInputFromKeyboard("Enter the new word: ");
for (int i = 0; i < array.length; i++){
if (array[i].equals(word)){
array[i] = newWord;
break;
}
}
Arrays.sort(array);
}
}
To read from the keyboard use
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader (isr);
String cadena = br.readLine();
And all the words you introduced form the keyboard will be in "cadena".
To separte all the words you introduced you could use the method split from String.class.
String[] words = cadena.split(" ");
To find a specific word you could use a method and the code would be in your method would be:
String yourWord = "";
for(int i = 0; i < words.length; i++)
{
if(words[i].equals("your word"))
{
yourWord = words[i];
break;
}
}
To replece a word use the method replce(theWord, "the replacement")
You can prints all the words using a loop for with System.out.println(yourWord);

Find common alphabets in two strings using for loop

I am trying to find the common characters in two strings just by using the for loop. The below code is working fine, if I provide two completely different strings ex.one and two but if I provide two strings with same input ex.teen and teen it doesn't work as expected.
import java.util.Scanner;
public class CommonAlphabets {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in)){
System.out.println("Enter String one ");
String stringOne = input.nextLine();
System.out.println("Enter String two ");
String StringTwo = input.nextLine();
StringBuffer sb = new StringBuffer();
for(int i=0;i<stringOne.length();i++){
for(int j=0;j<StringTwo.length();j++){
if(stringOne.charAt(i)== StringTwo.charAt(j)){
sb.append(stringOne.charAt(i));
}
}
}
System.out.println("Common characters are " +sb.toString());
}
}
}
Should I create another nested for loop to find duplicates in the StringBuffer or is there a better way to handle this scenario.
You do not need an inner for loop but use contains instead
String stringOne = "one";
String stringTwo = "one";
StringBuilder sb = new StringBuilder();
for(int i=0;i<stringOne.length() && i < stringTwo.length ();i++){
if(stringOne.contains(String.valueOf(stringTwo.charAt(i))) &&
!sb.toString().contains(String.valueOf(stringTwo.charAt(i)))){
// check already added
sb.append(stringTwo.charAt(i));
}
}
System.out.println (sb.toString());
edit
check to make sure char to be added does not already exist in StringBuilder -
Could use a Set instead
If using a Set
Set<Character> set = new HashSet<> ();
your logic could be simplified to
if(stringOne.contains(String.valueOf(stringTwo.charAt(i)))){
set.add(stringTwo.charAt(i));
}
You can use Set for it.
Set<Character> set = new HashSet<>();
for(int i = 0; i<stringOne.length(); i++) {
for(int j = 0; j < StringTwo.length(); j++) {
if(stringOne.charAt(i) == StringTwo.charAt(j)){
set.add(stringOne.charAt(i));
}
}
}
StringBuilder sb = new StringBuilder();
for (Character c : set) {
sb.append(c);
}
System.out.println("Common characters are " + sb);
well your approach is fine as the result is showing what you are expecting there fore that code is fine, but you need to stop the duplication , therefore you have to write the code for 'sb' variable so that it will remove duplicates or write code in loop so that it wont provide duplicate.
as your code is becoming complicated to read so i would prefer that you make a method to write code to remove duplicate it will go like
static void removeDuplicate(StringBuilder s){
for(int i=0,i<s.length-1,i++){
for(int j=i+1,j<s.length,j++){
if(s.charAt(i)==s.charAt(j)){
s.deleteCharAt(j);
}
}
}
call this method before printing
Another approach you could try is - combine the two input strings, iterate over the concatenated string and return the characters which exist in both the strings.
Using a Set will ensure you do not add characters which get repeated due to the concatenation of the strings.
Here's what I wrote -
import java.util.HashSet;
public class HelloWorld {
private static Character[] findCommonLetters(String combined, String w1, String w2) {
HashSet<Character> hash = new HashSet<>();
for(char c: combined.toCharArray()) {
if(w1.indexOf(c) != -1 && w2.indexOf(c) != -1) {
hash.add(c);
}
}
return hash.toArray(new Character[hash.size()]);
}
public static void main(String []args){
// System.out.println("Hello World");
String first = "flour";
String second = "four";
String combined = first.concat(second);
Character[] result = findCommonLetters(combined, first, second);
for(char c: result) {
System.out.print(c);
}
System.out.println();
}
}
Demo here.
This is the best way to do this because it's time complexity is n so that why this is the best you could do.
import java.util.Scanner;
public class CommonAlphabets
{
public static void main(String[] args)
{
try (Scanner input = new Scanner(System.in))
{
System.out.println("Enter String one ");
String stringOne = input.nextLine();
System.out.println("Enter String two ");
String StringTwo = input.nextLine();
StringBuffer sb = new StringBuffer();
/**
* Assuming char as index of array where A-Z is from index 0 to 25 and a-z is index 26-51
*/
int[] alphabetArray1 = new int[52];
for(int i = 0, len = stringOne.length(); i < len; i++)
alphabetArray1[stringOne.charAt(i) > 94 ? stringOne.charAt(i) - 71 : stringOne.charAt(i) - 65] = 1;
int[] alphabetArray2 = new int[52];
for(int i = 0, len = StringTwo.length(); i < len; i++)
alphabetArray2[StringTwo.charAt(i) > 94 ? StringTwo.charAt(i) - 71 : StringTwo.charAt(i) - 65] = 1;
// System.out.println(Arrays.toString(alphabetArray1));
// System.out.println(Arrays.toString(alphabetArray2));
for (int i = 0; i < 52; i++)
if (alphabetArray1[i] == 1 && alphabetArray2[i] == 1)
sb.append((char) (i < 26 ? i + 65 : i + 71));
System.out.println("Common characters are " + sb.toString());
}
}
}

+= operator not working with string

I'm trying to produce a program that outputs the user's input in a form like this:
input: word
w
wo
wor
word
This incremental build-up doesn't seem to be working.
import java.util.*;
public class SpellMan {
public static void main(String[] args) {
Scanner kb = new Scanner (System.in) ;
System.out.println("Give me a word > ");
String word = kb.nextLine();
for(int i = 0; i< word.length();i++){
String bword += ""+word.charAt(i);
System.out.println(bword);
}
}
}
You are declaring bword inside the loop, so in each iteration you attempt to concatenate the current character to an uninitialized String variable.
Try :
String bword = "";
for(int i = 0; i< word.length();i++) {
bword += word.charAt(i);
System.out.println(bword);
}
That said, using a StringBuilder would be more efficient (less objects will be created).
StringBuilder bword = new StringBuilder(word.length());
for(int i = 0; i< word.length();i++) {
bWord.append(word.charAt(i));
System.out.println(bword.toString());
}
Apart from other code problems, the main point concerning your question header is that you can not use += operator within the declaration, because bword is still null (It will not compile).
String bword = ""; //before the loop
bword += word.charAt(i);
System.out.println(bword);

Java returning a string from a stack

I am supposed to reverse the individual words in a sentence using a helper method that takes a string as a parameter and returns a string. The stack is supposed to be in the helper method. So my program works in that it reverses the words correctly. But reverse isnt actually getting returned, i think its just printing the stack. Can anyone help me return and print the string variable 'reverse'.
import java.util.Scanner;
import java.util.Stack;
public class ReverseStack
{
public static void main(String[] args)
{
String sentence;
System.out.print("Enter a sentence: ");
Scanner scan = new Scanner(System.in);
sentence = scan.nextLine();
System.out.println("Reversed:" + PrintStack(sentence));
}
private static String PrintStack(String sentence)
{
String reverse = "";
String next = "";
Stack<String> stack= new Stack<String>();
String words[] = sentence.split(" ");
for(int j = 1; j<words.length +1; j++)
{
String newWord = words[words.length - j]; // Single word
for(int i = 0; i < newWord.length(); i++)
{
next = newWord.substring(i,i+1);
stack.push(next);
}
stack.push(" ");
}
while(!stack.isEmpty())
{
reverse += stack.pop();
}
return reverse;
}
}
You are reversing twice and ending up with the same order. Your Stack gives reverse order, but you are adding the words in reverse order, so the order is unchanged.
If you used a debugger it should be obvious to you what the issues is.
BTW You can make the code much shorter.
private static String printStack(String sentence) {
Stack<String> stack= new Stack<String>();
for(String word: sentence.split(" ")
stack.push(word);
String line = stack.pop();
while(!stack.isEmpty())
line += " " + stack.pop();
return line;
}

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