Checking element in ArrayList between two double quotes - java

I'm writing a primitive version of programming language reader in Java for custom language that I made and I want to find out easiest way to print content of element from ArrayList that is located between two elements of double quotes. Here is source code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class PrimitiveCompiler {
public static ArrayList<String> toks = new ArrayList<String>();
public static void main(String[] args) throws FileNotFoundException {
String content = readFile("C:\\program.txt");
tokenize(content);
}
public static String readFile(String filePath) throws FileNotFoundException {
File f = new File(filePath);
Scanner input = new Scanner(f);
StringBuilder b = new StringBuilder();
while (input.hasNextLine()) {
b.append(input.nextLine());
}
input.close();
return b.toString();
}
public static ArrayList<String> tokenize(String fContent) {
int i = 0;
String tok = "";
String contents = fContent.replaceAll(" ", "").replaceAll("\n", "").replaceAll("\t", "");
for(int a = 0; a <= contents.length() - 1; a++) {
tok += contents.charAt(a);
i = a;
if(tokenFinderEquals(tok, "WRITE")) {
toks.add("WRITE");
tok = "";
}
}
System.out.println(toks);
return null;
}
public static boolean tokenFinderEquals(String s1, String s2) {
if(s1.equalsIgnoreCase(s2)) {
return true;
}
return false;
}
}
Content of text file right now is just WRITE and it succesfully finds it and add it to ArrayList. What I want to do is to count double quotes and when two double quotes are found in ArrayList to print out every element between them. Is it posibble or there's another, easier way to do this? Thanks in advance!

You'll need some kind of state to keep track of whether or not you're inside of a quote. For example:
boolean inQuote = false;
for (int a = 0; a <= contents.length() - 1; a++) {
char c = contents.charAt(a);
if (c == '"') {
// Found a quote character. Are we at the beginning or the end?
if (!inQuote) {
// Start of a quoted string.
inQuote = true;
} else {
// End of a quoted string.
inQuote = false;
toks.add(tok);
tok = "";
}
// Either way, we don't add the quote char to `tok`.
} else {
tok += c;
if (!inQuote && tokenFinderEquals(tok, "WRITE") {
// Only look for "WRITE" when outside of a quoted string.
toks.add(tok);
tok = "";
}
}
}
Using a simple loop like this can start to get tough as you add more cases, though. You may want to look into writing a recursive descent parser.

Related

java regex negate with boundaries (square bracktes)

I would appreciate if anybody could help me with a JAVA regex requirement
I got a String like "/ABC/KLM[XYZ/ABC/KLM]/ABC"
I want to replace all ABC not surround by square brackets.
In this case only the first and last ABC should be found.
But not ABC in the middle because it is surrounded with square brackets
You cannot do this without a recursive regular expression. Java does not support this within the standard libraries, but flavours of regex found in Perl or .NET do. This is in essence the same problem as trying to match content within HTML tags - by far the easiest way to do it is using a stack-based parser.
Solution is here:
public class MergeParentAndChildXPATH {
public static void main(String[] args) {
String substringToBeFound = "ABC";
String toReplayceWith = "XXX";
String xPathFromExcel = "/UTILMD/ABC/[XYZ/ABC/KLM]KLM[XYZ/ABC/[XYZ/ABC/KLM]KLM]/ABC";
System.out.println("original String\t"+xPathFromExcel);
String manupulatedString = mergeParentAndChildXPATH(substringToBeFound, toReplayceWith,xPathFromExcel);
System.out.println("manipulated String\t"+manupulatedString);
}
public static String mergeParentAndChildXPATH(String substringToBeFound, String toReplayceWith, String xPathFromExcel ) {
StringBuffer sbManipulatedString = new StringBuffer();
int lengthABC = substringToBeFound.length();
CharStack charStack = new CharStack();
String substringAfterMatch = "";
while (xPathFromExcel.indexOf(substringToBeFound)>-1) {
int matchStartsAt = xPathFromExcel.indexOf(substringToBeFound);
int matchEndssAt = xPathFromExcel.indexOf(substringToBeFound)+lengthABC;
String substringBeforeMatch = xPathFromExcel.substring(0, matchStartsAt);
substringAfterMatch = xPathFromExcel.substring(matchStartsAt+lengthABC);
String substringMatch = xPathFromExcel.substring(matchStartsAt, matchEndssAt);
// System.out.println("Loop Count\t"+loopCount);
// System.out.println("substringBeforeMatch\t"+substringBeforeMatch);
// System.out.println("substringAfterMatch\t"+substringAfterMatch);
// System.out.println("starts "+matchStartsAt+ " ends "+matchEndssAt);
// System.out.println("Output of match: "+substringMatch);
// now tokenize the string till match is reached and memorize brackets via Stack
String sTokenize = xPathFromExcel;
for (int i = 0; i < matchStartsAt; i++) {
char ch = sTokenize.charAt(0);
// System.out.println(ch);
// System.out.println(sTokenize.substring(0,1));
if (ch == '[') {
charStack.push(ch);
}
if (ch == ']') {
charStack.pop();
}
sTokenize = sTokenize.substring(1);
}//for
if (charStack.empty()) {
substringMatch = substringMatch.replaceAll(substringMatch, toReplayceWith);
}
//
sbManipulatedString.append(substringBeforeMatch + substringMatch);
// System.out.println("manipulatedString\t"+sbManipulatedString.toString());
xPathFromExcel = substringAfterMatch;
// System.out.println("remaining String\t"+substringAfterMatch);
}
return (sbManipulatedString.toString()+substringAfterMatch);
}
}
import java.util.Stack;
public class CharStack {
private Stack theStack;
CharStack() {
theStack = new Stack();
}
public char peek() {
Character temp = (Character) theStack.peek();
return temp.charValue();
}
public void push(char c) {
theStack.push(new Character(c));
}
public char pop() {
char temp = (Character) theStack.pop();
return temp;
}
public boolean empty() {
return theStack.empty();
}
}

Alternating string of characters and digits

I was given this problem to solve. I have only the slightest idea on how it should be implemented, and I'm all too new with programming and stuffs, and would love to hear your comments on this.
Say given a string in the form "abc1234defgh567jk89", and I must create a new string "a1b2c3d5e6f7j8k9".
Note that there are corresponding [digits] & [characters] group and since there may be more of one type over the other, the output has only matching sequence and ignore extra digits or characters in this case '4' & 'g' & 'h'.
I know I will have to use 2 sets of queues to store both types of elements, but I do not know how else to proceed from here.
Would appreciate if you could share a pseudocode or a Java(prefably) version, since I am learning thru this language now.
Thank you.
Pseudocode:
Queue letterQueue;
Queue numberQueue;
for (every character in the string) {
if (it's a letter) {
if (numberQueue is not empty) {
add the letters alternating into the buffer (stringbuilder), and purge buffers
}
add newest letter to letterqueue
}
if (it's a number) {
add newest letter to numberqueue
}
}
add any remaining unprocessed letters to the queue (this will happen most of the time)
return contents of string buffer
You will need:
Queue, probably a LinkedList
StringBuilder
String.toCharArray
Character
Code:
import java.util.LinkedList;
import java.util.Queue;
public class StringTest {
private static String str ="abc1234defgh567jk89";
private static String reorganize(String str) {
Queue<Character> letterQueue = new LinkedList<>();
Queue<Character> numberQueue = new LinkedList<>();
StringBuilder s = new StringBuilder();
for (char c : str.toCharArray()) {
if(Character.isLetter(c)) {
if (!numberQueue.isEmpty()) processQueues(letterQueue, numberQueue, s);
letterQueue.offer(c);
} else if(Character.isDigit(c)) {
numberQueue.offer(c);
}
}
processQueues(letterQueue, numberQueue, s);
return s.toString();
}
private static void processQueues(Queue<Character> letterQueue, Queue<Character> numberQueue, StringBuilder s) {
while(!letterQueue.isEmpty() && !numberQueue.isEmpty()) {
s.append(letterQueue.poll());
s.append(numberQueue.poll());
}
letterQueue.clear();
numberQueue.clear();
}
public static void main(String... args) {
System.out.println(reorganize(str));
}
}
See this hint:
String str = "abc1234defgh567jk89";
String c = str.replaceAll("\\d", ""); // to store characters
String d = str.replaceAll("\\D", ""); // to store digits
Try this:
public static void main(String[] args) {
String str = "abc1234defgh567jk89";
String c = str.replaceAll("\\d", "");
String d = str.replaceAll("\\D", "");
String result = "";
int j = 0, k = 0;
int max = Math.max(c.length(), d.length());
for (int i = 0; i < max; i++) {
if (j++ < c.length())
result = result + c.charAt(i);
if (k++ < d.length())
result = result + d.charAt(i);
}
System.out.println(result);
}
Output:
a1b2c3d4e5f6g7h8j9k

File tokenization in java

The below code is for tokenization in java. I am having a small bug which I am just not able to fix. This is regarding file tokenization. In this code, if a user enters four capital words in a file. It is not supposed to be tokenised and is supposed to be retained at the same line. The rest of the words have to be tokenized if there is no capital letter or anything.
For example
United States Of America
Hi I am Walt.
The O/P is supposed to look like this below.
United States Of America
Hi
I
am
Walt.
This is how it's supposed to look like. After I wrote my code I am facing a small bug.
The O/P is showing up like this.
United States Of America
States
Of
America
Hi
I
am
Walt.
Basically I need to get rid of "States Of America". In the piece of code where I am checking for uppercase. Could you please help me in solving this problem, as I am just not able to get my around it? Anything to make this possible will be helpful.
Please feel free to alter my code and try getting my output.
import java.io.*;
import java.util.*;
public class Tokenize {
public static void main (String[] args) {
try {
BufferedReader inputReader=new BufferedReader(new FileReader("C:/Users/Advait/Desktop/nlp_wikipedia.txt"));
String currentLine;
while ((currentLine = inputReader.readLine())!=null) {
// START STUDENT CODE
char atUpper;
char atUpper1;
int keeper = 1;
int keeper1 = 0;
String temp = "";
int j;
int i;
int counter = 0;
int m=0;
int n=0;
String temp1 = "";
boolean boolKeeper,boolKeeper1;
String Delimeter = "[\\s,:;'!?()\"]+";
for(j=0;j<(currentLine.length()-1);j++) {
if(currentLine.contains("://")) {
currentLine=currentLine.replace("://","#");
}
}
String token1[] = currentLine.split(Delimeter);
for(j=0;j<(token1.length)-1;j++) {
if(j>0) {
if(keeper==0) {
atUpper = token1[j+1].charAt(0);
atUpper1 = token1[keeper].charAt(0);
boolKeeper = Character.isUpperCase(atUpper);
boolKeeper1 = Character.isUpperCase(atUpper1);
if(boolKeeper==true && boolKeeper1==true) {
m++;
temp1 = token1[keeper].concat(" ").concat(token1[j+1]);
token1[keeper] = temp1;
}
} else {
i=j+1;
atUpper = token1[j].charAt(0);
atUpper1 = token1[i].charAt(0);
boolKeeper = Character.isUpperCase(atUpper);
boolKeeper1 = Character.isUpperCase(atUpper1);
if(boolKeeper==true && boolKeeper1==true) {
counter=counter+1;
if(counter == 1) {
keeper1 = j;
}
n++;
temp = token1[keeper1].concat(" ").concat(token1[i]);
token1[keeper1] = temp;
}
}
} else {
i=j+1;
atUpper = token1[j].charAt(0);
atUpper1 = token1[i].charAt(0);
boolKeeper = Character.isUpperCase(atUpper);
boolKeeper1 = Character.isUpperCase(atUpper1);
if(boolKeeper==true && boolKeeper1==true) {
keeper = 0;
m++;
temp = token1[j].concat(" ").concat(token1[i]);
token1[j] = temp;
}
}
ArrayList<String> LineList = new ArrayList<String>();
for (String token : token1) {
if (!token.equals("%")) {
LineList.add(token);
}
}
token1 = LineList.toArray(new String[LineList.size()]);
String token2 = token1[j];
for (int l=0;l<(token2.length()-1);l++) {
if(token2.charAt(l) == '-' && token2.charAt(l+1) == '\n') {
String token3[] = token2.split("-");
token1[j] = token3[0] + token3[1];
}
}
}
for(int k=0;k<(token1.length);k++) {
if(token1[k].contains(".") && token1[k].contains("#")) {
token1[k] = token1[k].replace(".", "*");
}
if(token1[k].contains("#") && token1[k].contains(".")) {
token1[k] = token1[k].replace("#","://");
token1[k] = token1[k].replace(".","*");
}
}
for(int k=0;k<(token1.length);k++) {
StringTokenizer st = new StringTokenizer(token1[k],".");
while (st.hasMoreTokens()) {
token1[k] = st.nextToken();
}
}
for(int k=0;k<(token1.length);k++) {
String token4 = token1[k];
for (int l=0;l<(token4.length()-1);l++) {
if(token4.contains("#") && token4.contains("*")) {
token1[k] = token4.replace("*",".");
}
if(token1[k].contains("://") && token1[k].contains("*")) {
token1[k] = token4.replace("*",".");
}
}
}
for(int k=0;k<(token1.length);k++) {
System.out.println(token1[k]);
}
// END STUDENT CODE
}
}
catch (IOException e) {
System.err.println("Caught IOException: "+e.getMessage());
}
}
}
Your first problem is that you are cramming everything into a single huge function. You need to split the code into meaningful units that each perform a well-defined, easily-understood operation. For the specific issue of capitalized words, I recommend a function int capitalizedWordStreakLength(String[] tokens, int i). You can use that function in a loop that assembles a List<String> of resulting tokens by iterating over the String[] of your "raw" tokens and, if that function returns four or more, concats those words into a single token.

How to disregard numbers when reading from a text file?

Right now I want to store a text file that goes like this:
1 apple
2 banana
3 orange
4 lynx
5 cappuccino
and so on into a data structure. Would the best way of doing this be mapping the int to the string somehow, or should I make an arraylist? I'm supposed to, when I store the words themselves, disregard the int and any whitespace, and keep only the word itself. How do I disregard the int when reading in lines? Here is my hacked together code right now:
public Dictionary(String filename) throws IOException {
if (filename==null)
throw new IllegalArgumentException("Null filename");
else{
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
int numLines=0;
while ((str = in.readLine()) != null) {
numLines++;
}
String[] words=new String[numLines];
for (int i=0; i<words.length;i++){
words[i]=in.readLine();
}
in.close();
} catch (IOException e) {
}
}
}
Thank you in advance for the help!!
Just implement the power of the regular expression:
List texts<String> = new ArrayList<String>();
Pattern pattern = Pattern.compile("[^0-9\\s]+");
String text = "1 apple 2 oranges 3 carrots";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
texts.add(matcher.group(0));
}
regular expressions are very much popular these days. the compile method is used for compiling your search pattern, with the numbers you see in the parameter is to prevent getting them on your search. So it's completely safe. use apache's IOUtilities to convert a text file to String
This won´t work because you are already at the end of the file, so the in.readLine() methode will return null.
I would use a Map to store the name and the amount...something like this:
HashMap<String, Integer> map = new HashMap<String, Integer>();
while( (line = br.readLine() !=null){
//also check if the array is null and the right size, trim, etc.
String[] tmp = line.split(" ");
map.put(tmp[1], Integer.parseInt(tmp[0]) );
}
Otherwise you can try it with the Scanner class. Good luck.
You can give regular expressions a try.
Pattern p = Pattern.compile("[^0-9\\s]+");
String s = "1 apple 2 oranges";
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(0));
}
Output =
apple
oranges
To get a idea about regular expressions Java regex tutorial.
I suggest you use a List of items to store the results parsed from the file. One way to parse every text line is to use the String.split(String) method. Also note that you should handle exceptions in the code properly and do not forget to close the Reader when you are done (no matter whether flawlessly or with an exception => use a finally block). The following example should put you on track... Hope this helps.
package test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
Main m = new Main();
m.start("test.txt");
}
private void start(String filename) throws IOException {
System.out.println(readFromFile(filename));
}
private final class Item {
private String name;
private int id;
public Item(String name, int id) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Item [name=" + name + ", id=" + id + "]";
}
}
private List<Item> readFromFile(String filename) throws IOException {
List<Item> items = new ArrayList<Item>();
Reader r = null;
try {
r = new FileReader(filename);
BufferedReader br = new BufferedReader(r);
String line = null;
while ((line = br.readLine()) != null) {
String[] lineItems = line.split(" ");
if (lineItems.length != 2) {
throw new IOException("Incorrect input file data format! Two space separated items expected on every line!");
}
try {
int id = Integer.parseInt(lineItems[0]);
Item i = new Item(lineItems[1], id);
items.add(i);
} catch (NumberFormatException ex) {
throw new IOException("Incorrect input file data format!", ex); // JDK6+
}
}
} finally {
if (r != null) {
r.close();
}
}
return items;
}
}
If your words don't contain spaces, you could use String.split( " " ) to split up the String into an array of Strings delimited by spaces.
Then just take the second element of the array (the first will be the number).
Also, the String.trim( ) method will remove any whitespace before or after the String.
Note: there's probably some error checking that you'd want to perform (what if the String isn't formatted as you expect). But this code snippet gives the basic idea:
...
String s = in.readLine( );
String[] tokens = s.split( " " );
words[i] = tokens[1].trim( );
...
If you want to do something easy just substring the original work by counting digits:
int t = 0;
while (word.charAt(t) >= '0' && word.charAt(t) <= '9')
++t;
word = word.substring(t);
If words NEVER contain spaces you can also use word.split(" ")[1]
Instead of using a buffer reader use the Scanner class and instead of using an Array use an ArrayList, like so :
import java.util.Scanner;
import java.util.ArrayList;
public class Dictionary {
private ArrayList strings = new ArrayList();
code...
public Dictionary(String fileName) throws IOException {
code...
try {
Scanner inFile = new Scanner(new fileRead(fileName));
ArrayList.add("Dummy"); // Dummy value to make the index start at 1
while(inFile.hasNext()) {
int n = inFile.nextInt(); // this line just reads in the int from the file and
// doesn't do anything with it
String s = inFile.nextLine().trim();
strings.add(s);
}
inFile.close(); // don't forget to close the file
}
and then since your data goes 1, 2, 3, 4, 5, you can just use the index to retrieve each item's number.
By doing this:
for(int i = 1; i < strings.size(); i++) {
int n = i;
String s = n + " " + strings.get(i);
System.out.println(s);
}

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