How to convert char to String in tokenizer in Java - java

Trying to read a file separated by commas into an array and not sure how to make party into a string to work with tokenizer
for(int i = 0; i < s.length; i++) {
String str = scan.nextLine();
StringTokenizer st = new StringTokenizer(str, ",");
//String [] tokens = str.split(",");
String name = st.nextToken();
String abbreviation = st.nextToken();
long population = Long.parseLong(st.nextToken());
String govName = st.nextToken();
char party = st.nextToken();
int ageWhenElected = Integer.parseInt(st.nextToken());
s[i] = new State(name, abbreviation, population, govName ,party, ageWhenElected);

Try
char party = st.nextToken().charAt(0);

You can join your array of string with comma as separator
StringUtils.join(strArray, ",");

Related

Reverse a string as per length of first word

I am new to Java Strings.
Actually I have the code to reverse words:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test2 {
public static void main(String[] args) throws IOException
{
System.out.println("enter a sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String rev =br.readLine();
String [] bread = rev.split(" ");
for(int z =bread.length-1;z>=0;z--)
{
System.out.println(bread[z]);
}
}
}
For the above code I get:
Input :Bangalore is a city
Output: City is a Bangalore
But I want the output to be like below:
Input: Bangalore is a city
Output:cityaisba ng a lore
Another Example:
Input: Hello Iam New To Java.Java is object Oriented language.
Output: langu age Ori en tedo bjec ti sjava. javaToNe wIamolleH
Please help me out
Here is one way you could do it:
String rev = br.readLine();
String [] bread = rev.split(" ");
int revCounter = 0;
for(int z = bread.length - 1; z >= 0; z--)
{
String word = bread[z];
for(int i = 0; i < word.length(); i++)
{
// If char at current position in 'rev' was a space then
// just print space. Otherwise, print char from current word.
if(rev.charAt(revCounter) == ' ')
{
System.out.print(' ');
i--;
}
else
System.out.print(word.charAt(i));
revCounter++;
}
}
When I run your code I get following result:
city
a
is
Bangalore
So to have it in a single line, why don't you add a space and print a single line?
System.out.println("enter a sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String rev = br.readLine();
String[] bread = rev.split(" ");
for (int z = bread.length - 1; z >= 0; z--) {
System.out.print(bread[z] + " ");
}
I didn't check the validity of your code like GHajba did. But if you want spaces to remain on specific places it might be an option to remove all spaces and put them back according to their index in the original String.
Remove all
newBread = newBread.replace(" ", "");
Put them back
StringBuilder str = new StringBuilder(newBread);
for (int index = oldBread.indexOf(" ") ;
index >= 0 ;
index = oldBread.indexOf(" ", index + 1))
{
str.insert(index, ' ');
}
newBread = str.toString();
I came up with this quick and there might be better ways to do this, maybe without StringBuilder, but this might help you until you find a better way.
Try with this (i've used a string as input):
String original = "Bangalore is a city";
System.out.println("Original : "+original);
StringBuilder inverted = new StringBuilder();
StringBuilder output = new StringBuilder();
String temp = "";
String[] split = original.split("\\s+");
for (int i = split.length - 1; i >= 0; i--) {
inverted.append(split[i]);
}
temp = inverted.toString();
for (String string : split) {
int currLenght = string.length();
String substring = temp.substring(0,currLenght);
temp = temp.replaceAll(substring, "");
output.append(substring).append(" ");
}
System.out.println("Converted : "+output.toString());
Append the reversed words without the spaces into a StringBuffer.
StringBuffer b = new StringBuffer();
for (int i = bread.length-1; i >= 0 ; i--) {
b.append(bread[i]);
}
Then insert the spaces of the original String into the StringBuffer.
int spaceIndex, prevIndex = 0;
while ((spaceIndex = rev.indexOf(" ", prevIndex + 1)) != -1) {
b.insert(spaceIndex, ' ');
prevIndex = spaceIndex;
}

Make Multiple Strings with For Loop

So I have a text file reader that reads in each string as they come in.
String R1Name = fileScanner.nextLine();
String R1URL = fileScanner.nextLine();
String R2 = fileScanner.nextLine();
String R2Name = fileScanner.nextLine();
String R2URL = fileScanner.nextLine();
String R3 = fileScanner.nextLine();
String R3Name = fileScanner.nextLine();
String R3URL = fileScanner.nextLine();
Etc.
How can I have it so it creates a simple for loop with number 1-7 that does the same thing with less code?
for(int i=0; i<8; i++){
String R(i) = fileScanner.nextLine();
String R(i)URL=fileScanner.nextLine();
}
Trying to get something like this but with no luck
You can use an array:
String[] R = new String[8];
String[] RUrl = new String[8];
for(int i = 0; i < 8; i++)
{
R[i] = fileScanner.nextLine();
RUrl[i] = fileScanner.nextLine();
}

Tokenize devnagari words into letters

I have something like
a = "बिक्रम मेरो नाम हो"
I want to achieve something like in Java
a[0] = बि
a[1] = क्र
a[3] = म
Java internally stores each character of any language in UTF-16(2 bytes) so you can safely access the characters individually.
Try This:
String a = "बिक्रम मेरो नाम हो";
int strLen = a.length();
char array[] = new char[strLen];
String strArray1[] = new String[strLen];
for (int i=0 ; i< strLen ; i++)
{
array[i] = a.charAt(i);
strArray1[i] = Character.toString(a.charAt(i));
System.out.println ("Index = " + i + "* Char = " +array[i] + "** String =" +strArray1[i] );
}
Output:
Index = 0* Char = ब** String =ब
Index = 1* Char = ि** String =ि
Index = 2* Char = क** String =क
Index = 3* Char = ्** String =्
Index = 4* Char = र** String =र
Index = 5* Char = म** String =म
Index = 6* Char = ** String =
Index = 7* Char = म** String =म
Index = 8* Char = े** String =े
Index = 9* Char = र** String =र
Index = 10* Char = ो** String =ो
Index = 11* Char = ** String =
Index = 12* Char = न** String =न
Index = 13* Char = ा** String =ा
Index = 14* Char = म** String =म
Index = 15* Char = ** String =
Index = 16* Char = ह** String =ह
Index = 17* Char = ो** String =ो
Note:
In order to allow eclipse to allow you to save your java program with foreign characters(Hindi alphabets), do the following:
Go to:
"Windows > Preferences > General > Content Types > Text > {Choose file type}
{Selected file type} > Default encoding > UTF-8" and click Update.
Did you try icu4j?
BreakIterator character instance has a possibility to split String to characters
My code is not at all optimized, sorry about that but it works!
Just change the path of the file in which you are going to enter the devnagri sentence and it should work.
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("/home/ubuntu/Documents/trainforjava.txt")); //PLEASE ENTER PATH HERE
String[] devFull = new String[]{
"अ","आ", "इ", "ई", "उ", "ऊ", "ऋ"
, "ऌ" ,"ऍ", "ए", "ऐ", "ऑ", "ओ", "औ",
"क", "ख", "ग", "घ" ,"ङ",
"च" ,"छ" ,"ज"," झ"," ञ",
"ट","ठ", "ड"," ढ"," ण",
"त", "थ", "द", "ध", "न",
"प", "फ", "ब"," भ","म",
"य", "र", "ल", "ळ",
"व", "श" ,"ष","स" ,"ह"
};
String[] uniDev = new String[]
{
"905","906","907","908","909","90a","90b",
"90c","90d","90f","910","911","913","914",
"915","916","917","918","919",
"91a","91b","91c","91d","91e",
"91f","920","921","922","923",
"924","925","926","927","928",
"92a","92b","92c","92d","92e",
"92f","930","932","933",
"935","936","937","938","939"
};
String[] devHalf = new String[]
{
"$़","ऽ","$ा","$ि" ,
"$ी", "$ ु","$ू","$ृ","$ॄ","$ॅ",
"$े","$ै","$ॉ",
"$ो","$ौ"
};
String[] gujHalf = new String[]
{
"$઼","ઽ","$ા","$િ" ,
"$ી","$ુ","$ૂ","$ૃ","$ૄ","$ૅ",
"$ે","$ૈ","$ૉ",
"$ો","$ૌ"
};
try
{
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while( (line = br.readLine() ) != null)
{
line=line.replaceAll(" ", ""); //remove white spaces if any
System.out.println();
//System.out.println(line);
int strLength = line.length();
// String a = "बिक्रम मेरो नाम हो";
int strLen = line.length();
char array[] = new char[strLen];
String strArray1[] = new String[strLen];
int mark[] = new int[strLen+1];
String unis[]=new String[strLen];
int cnt=0;
String newCharD[]=new String [strLen];
String newCharG[]=new String [strLen];
String tempD=null;
String tempG=null;
String arr = null;
String next =null;
String temp=null;
String uniNext=null;
int hold=0;
int j=0;
for (int i=0 ; i< strLen ; i++)
{
j=i+1;
array[i] = line.charAt(i);
strArray1[i] = Character.toString(line.charAt(i));
if(i<(strLen-1))
{
char nbit = line.charAt(j);
next=Character.toString(line.charAt(j));
uniNext=Integer.toHexString(nbit);
//System.out.print("\nUninext:\t"+uniNext);
}
unis[i]=Integer.toHexString(array[i]);
mark[strLen]=1;
if((Arrays.asList(devFull).contains(Character.toString(array[i]))) && (!uniNext.equalsIgnoreCase("94d")) )
{
mark[i]=1;
}
else
{
mark[i]=0;
}
//
//System.out.println();
//System.out.println ("Index = " + i + "* Char = " +array[i] + "** String =" +strArray1[i]+ "Unicode="+unis[i]+"Mark="+mark[i]);
//System.out.print(unis[i].toString());
}
int start=0;
start=0;
for(int l1=0;l1<=strLen;l1++)
{
//start=0;
if(l1==0)
{
temp=Character.toString(array[l1]);
}
else
{
if(mark[l1]==0)
{
temp=temp+Character.toString(array[l1]);
}
else
{
System.out.print(" "+temp);
newCharD[start]=temp;
start++;
temp=null;
if(l1!=strLen)
{
temp=Character.toString(array[l1]);
}
}
}
}
/* for(int s=0;s<start;s++)
{
System.out.print(" "+newCharD[s]);
}*/
for(int s=0;s<start;s++)
{
}
}
}
finally {
br.close();
}
//PrintStream out = new PrintStream(new //FileOutputStream("/home/ubuntu/Documents/trainforjavaoutput.txt"));
//System.setOut(out);
}
Try this for Hindi :-
import java.io.*;
import java.text.BreakIterator;
import java.util.Locale;
public class Test {
public static void main(String[] args) throws IOException
{
String text = "बिक्रम मेरो नाम हो";
Locale hindi = new Locale("hi", "IN");
BreakIterator breaker = BreakIterator.getCharacterInstance(hindi);
breaker.setText(text);
int start = breaker.first();
for (int end = breaker.next();
end != BreakIterator.DONE;
start = end, end = breaker.next()) {
System.out.println(text.substring(start,end));
}
}
}
OUTPUT:-
बि
क्र
म
मे
रो
ना
म
हो
BreakIterator Java Documentation: https://docs.oracle.com/javase/tutorial/i18n/text/about.html
In order to split the string by letters rather than characters, going by dvasanth's suggestion, you can try below:
String x = "बिक्रम मेरो नाम हो";
x=x.replaceAll(" ", ""); // Remove all spaces
int strLength = x.length();
String [] letterArray = new String (strLength /2);
String combined = "";
for (int i=0, j=0; i < strLength ; i=i+2,j++)
{
strArray1[i] = Character.toString(x.charAt(i));
if (i+1 < strLength)
{
strArray1[i+1] = Character.toString(x.charAt(i+1));
combined = strArray1[i]+strArray1[i+1]; // This line provides the letters.
// Assumption is that each letter is 2 unicode characters long.
}
else
{
combined = strArray1[i];
}
letterArray [j] = combined;
System.out.println("Split string by letters is : "+combined);
System.out.println("Split string by letters in array is : "+letterArray [j]);
}
Output is:
Split string by letters is : बि
Split string by letters is : क्
Split string by letters is : रम
Split string by letters is : मे
Split string by letters is : रो
Split string by letters is : ना
Split string by letters is : मह
Split string by letters is : ो
Note:
In order to allow eclipse to allow you to save your java program with foreign characters(Hindi alphabets), do the following:
Go to:
"Windows > Preferences > General > Content Types > Text > {Choose file type}
{Selected file type} > Default encoding > UTF-8" and click Update.

Divide String by StringTokenizer and then save to 2 arrays

Imagine this array.
data[0] : 208.92.249.53:80
data[1] : 115.124.65.74:3128
data[2] : 49.213.17.92:8080
I want to split data[]. And extract ip and port number.
ip[0] : 208.92.249.53
ip[1] : 115.124.65.74
ip[2] : 49.213.17.92
port[0] : 80
port[1] : 3128
port[2] : 8080
How can I do that?
StringTokenizer stringTokenizer = new StringTokenizer(data[i], ":");
while (stringTokenizer.hasMoreTokens()){
//??????
}
I don't know how can I save to 2 different array. please let me show how to do that... Thank you!
String[] ip = new String[data.length];
String[] port = new String[data.length];
for (int i=0;i<data.length;i++) {
String[] split = data[i].split(":");
ip[i] = split[0];
port[i] = split[1];
}
StringTokenizer ist deprecated use array.split() instead.
String[] tmp = data[i].split(":");
ip[i] = tmp[0];
port[i] = tmp[1];
Try,
for(int i=0;i<data.length;i++){
StringTokenizer stringTokenizer = new StringTokenizer(data[i], ":");
while (stringTokenizer.hasMoreTokens()) {
ip[i]=stringTokenizer.nextToken();
port[i]=stringTokenizer.nextToken();
}
}
String[] arrTokens =data[0].split(":");
Maybe StringTokenizer is not what you want. You can do this via split command
String[] ip = new String[data.length];
String[] port = new String[data.length];
for (int i = 0; i < data.length; i++)
{
String[] splitted = data[i].split(":");
ip[i] = splitted[0];
port[i] = splitted[1];
}

Parsing an array to String Tokeniser

I have an object declared in this format
StringTokenizer star = new StringTokenizer(st , SEPARATOR); //separator is '/'
Session s1 = new Session(int SessionID, String [] cineName, String[] cineType, String movieName, String date, int time);
int SessionID = Integer.parseInt(star.nextToken().trim()); //for integer
String movieName = star.nextToken().trim(); //for string
String [] cineName = ? //how about string array?
Thus, I wish to ask how I can implement the parsing of a cineName array.
You can store the tokens of a String which delimits tokens with "/" in cineArray as follows:
int tokens = star.countTokens();
for (int i=0;i<tokens;i++)
{
cineName[i] = star.nextToken().trim();
}
String [] cineName = star.nextToken().trim().split(CINE_NAME_ARRAY_SEPARATOR);

Categories