Read nth line from string - java

i am trying to read 7th line of a string so that i can filter the required text but not getting more.(assuming i have n number of line).
class Lastnthchar {
public static void main(String[] args) {
// TODO Auto-generated method stub
String alldata =" FORM"+"\n"+
" to get all data"+"\n"+
" PART A is mandatory"+"\n"+
" enclose all Certificate"+"\n"+
" Certificate No. SFDSFDFS Last updated on 12-Jun-2009"+"\n"+
" Name and address"+"\n"+
" Lisa Lawerence"+"\n"+
" 10/3 TOP FLOOR, Street no 22 ,NewYork"+"\n"+
" residence"+"\n"+
" zip-21232"+"\n"+
" C 78,New York"+"\n"+
" US"+"\n"+
" US"+"\n"+
" "+"\n"+
" worldwide";
String namerequired = new String ();
//BufferedReader br = new BufferedReader(alldata);
int lineno = 0;
for(lineno = 0; lineno <alldata.length(); lineno ++)
{
//what should i do?
}
}
}
so if any solution please help.

alldata.length() will return the length of the string (i.e. number of characters), not the number of lines.
To get the nth line you'll need to split the string at the line breaks, e.g.
alldata.split("\n")[6] to get the 7th line (provided there are at least 7 lines).
This also assumes you have line breaks (\n) in your string and not just carriage returns (\r). If you want to split at both individually or in combination, you can change the parameter of split() to "\r\n|\n|\r". If you want to skip empty lines, you can split at any sequence of at least one line break or carriage return, e.g. "[\r\n]+".
Example:
System.out.println("--- Input:");
String input = "A\nB\rC\n\nD\r\nE";
System.out.println(input);
System.out.println("--- 4th element, split by \\n:");
System.out.println(input.split("\n")[3]); //3rd element will be "D\r"
System.out.println("--- 4th element, split by \\r\\n|\\n|\\r:");
System.out.println(input.split("\r\n|\n|\r")[3]); //3rd element will be an empty string
System.out.println("--- 4th element, split by [\\r\\n]+:");
System.out.println(input.split("[\r\n]+")[3]); //3rd element will be "D"
System.out.println("--- END");
Output:
--- Input:
A
B
C
D
E
--- 4th element, split by \n:
D
--- 4th element, split by \r\n|\n|\r:
--- 4th element, split by [\r\n]+:
D
--- END
Alternatively, if you're reading the text from some stream (e.g. from a file) you can use BufferedReader#readLine() and count the lines. Additionally you can initialize the BufferedReader with a FileReader, StringReader etc., depending on where you read the input from.
If you're reading from the console, the Console class also has a readLine() method.

If you use the BufferedReader you could do the following:
class Lastnthchar {
public static void main(String[] args) throws IOException {
String alldata =" FORM"+"\n"+
" to get all data"+"\n"+
" PART A is mandatory"+"\n"+
" enclose all Certificate"+"\n"+
" Certificate No. SFDSFDFS Last updated on 12-Jun-2009"+"\n"+
" Name and address"+"\n"+
" Lisa Lawerence"+"\n"+
" 10/3 TOP FLOOR, Street no 22 ,NewYork"+"\n"+
" residence"+"\n"+
" zip-21232"+"\n"+
" C 78,New York"+"\n"+
" US"+"\n"+
" US"+"\n"+
" "+"\n"+
" worldwide";
BufferedReader br = new BufferedReader(new StringReader(alldata));
String namerequired;
String line;
int counter = 0;
while ((line = br.readLine()) != null) {
if (counter == 6) {
namerequired = line;
}
counter++;
}
}
}

One way to approach your problem is to check index of "\n" specified amount of times until you find the line you need. I'm writing this off the top of my head so i'm sorry if syntax is not 100% accurate, but the logic is here:
public String readSpecifiedLine(String str, int lineNumber){
int lineStartIndex = 0;
//start by finding start of specified line
for(int i=0;i<lineNumber;i++){
lineStartIndex = str.IndexOf("\n",lineStartIndex); //find new line symbol from
//specified index
lineStartIndex++; //increase the index by 1 so the to skip newLine Symbol on
//next search or substring method
//Note, you might need to increase by 2 if "\n" counts as 2 characters in a string
}
int nextLine = str.IndexOf("\n",lineStartIndex); //end of line 7
retrun str.substring(lineStartIndex,nextline);
}
You might need to play around with indexes

Related

java: splitting one array into two separate arrays based on even and odd positions of the array

I'm new to Java and I'm having difficulties I have an assignment that requires me to load a text file with the name of a state followed by its capital onto the program and read the state names into one array and the capital names into another array. The way I tackled this was that I loaded the text file into one array called total and made a count. I wanted to split those with an even position to be in a separate array called capital and those in an odd position to be in an array called states. But I'm not sure how exactly to put that into code. This is what I have so far
Sample of Text File:
Alabama
Montgomery
Alaska
Juneau
Arizona
Phoenix
Arkansas
Little Rock
California
Sacramento
Colorado
Denver
Connecticut
Hartford
Delaware
Dover
Florida
Tallahassee
Georgia
Atlanta
Hawaii
Honolulu
And my code so far
public class StateCapitals
{
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException
{
File inputfile;
File outputfile;
inputfile = new File("capitals.txt");
outputfile = new File ("InOrder.txt");
String stateandcity;
int count;
count = 1;
PrintWriter pw;
Scanner kb;
kb = new Scanner(inputfile);
String [] total;
total = new String[100];
String [] capitals;
capitals = new String[50];
String [] states;
states = new String [50];
while (kb.hasNextLine())
{
stateandcity = kb.nextLine();
System.out.println("Count: " +count + " " + stateandcity);
total[count-1] = stateandcity;
count ++;
}
if (count % 2 == 0)
states = new String [50]; //where i need help
}}
The algorithm will be like this:
Read everything into total like you have already thought of.
Use a for loop to loop from i=0 to i=100 (or however many items there are to be split), incrementing by 2 each time.
Assign total[i] to capital[i / 2].
Assign total[i + 1] to states[i / 2].
It is as simple as that! Try doing it yourself first. If you are having difficulties, just leave a comment!
I would separate them while reading them like this. (Save yourself a loop)
while (kb.hasNextLine())
{
state[count] = kb.nextLine();
capitals[count] = kb.nextLine();
System.out.println("Count: " +count + " " +
state[count] + "," +
capitals[count]);
count ++;
}

useDelimeter(",") not working

I have a text file that holds data like this:
Jones,Mary,903452
4342,2.5,A
3311,4,B+
I'm using Scanner to read the file. This is my code:
while(reader.hasNextLine())
{
reader.useDelimiter(",");
String lastN = reader.next();
String firstN = reader.next();
String id = reader.nextLine();
String course1 = reader.next();
double credits = reader.nextDouble();
String grade = reader.nextLine();
}
But when I print the line on the console, the , on the last part of the line doesn't get delimited and it prints like this:
Jones, Mary, ,903452
4342, 2.5, ,A
6.5, ,3.569
My toString method on my class:
public String toString() {
return lastName + ", " + firstName + ", " + idNo + "\n"
+ courseOne + ", " + credits + ", " + grade;
I'm searched around for a solution. I tried reader.useDelimiter("[,]") and reader.useDelimiter(",|,") but still gives me the same output. How can I fix this?
From the Scanner's documentation:
This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
(Emphasis mine) This means that the whole rest of the line is returned, including delimiters. Setting id to reader.next() wouldn't work because it sucks up everything until the next delimiter. A better solution would be to make it accept line breaks as a delimiter, like so:
reader.useDelimiter("[,\n]");

How do I define the end of a string in Java?

I have a string that a user inputs their name in [Last, First Middle] format and I need to change it to [First Middle Last] format.
I've defined the last name as LFM.substring(0, commaSpace) . commaSpace being the name for the ", " in the input of the LFM (Last, First Middle) user input.
Then I needed to define firstMiddle . My question to you is, how could I define the end of the string LFM so I can have firstMiddle be LFM.substring(commaSpace, (end of string) ); ? That way I can just print firstMiddle + last .
ALL OF MY CURRENT CODE:
(IT'S REALLY MESSY, SORRY)
System.out.println();
System.out.println("This program will separate and convert a name in [Last, First, Middle] format to [First Middle Last].");
System.out.println();
System.out.print("Please enter a name in [Last, First Middle] format. ");
Scanner userInput = new Scanner(System.in);
String lineSeparator = System.getProperty("line.separator");
String LFM, first, middle, last, firstMiddle;
int commaSpace, end, lastLength;
userInput.useDelimiter(lineSeparator);
LFM = userInput.nextLine();
commaSpace = LFM.indexOf(",");
last = LFM.substring(0, commaSpace);
lastLength = last.length();
firstMiddle = LFM.substring(commaSpace, //?);
first = LFM.substring(commaSpace + firstMiddle.length());
System.out.println(firstMiddle + (" ") + last);
Use replaceAll or replaceFirst functions since it accepts regex as first argument.
string.replaceAll("^(\\w+),\\s*(\\w+)\\s+(\\w+)$", "$2 $3 $1");
DEMO

Having an issue with formatting a String input

I'm trying to get the input that the user enters to go to lower-case and then put the first character in the input to upper-case. For example, If I enter aRseNAL for my first input, I want to format the input so that it will put "Arsenal" into the data.txt file, I'm also wondering if there's a way to put each first character to upper-case if there's more than one word for a team ie. mAN uNiTeD formatted to Man United to be written to the file.
The code I have below is what i tried and I cannot get it to work. Any advice or help would be appreciated.
import java.io.*;
import javax.swing.*;
public class write
{
public static void main(String[] args) throws IOException
{
FileWriter aFileWriter = new FileWriter("data.txt");
PrintWriter out = new PrintWriter(aFileWriter);
String team = "";
for(int i = 1; i <= 5; i++)
{
boolean isTeam = true;
while(isTeam)
{
team = JOptionPane.showInputDialog(null, "Enter a team: ");
if(team == null || team.equals(""))
JOptionPane.showMessageDialog(null, "Please enter a team.");
else
isTeam = false;
}
team.toLowerCase(); //Put everything to lower-case.
team.substring(0,1).toUpperCase(); //Put the first character to upper-case.
out.println(i + "," + team);
}
out.close();
aFileWriter.close();
}
}
In Java, strings are immutable (cannot be changed) so methods like substring and toLowerCase generate new strings - they don't modify your existing string.
So rather than:
team.toLowerCase();
team.substring(0,1).toUpperCase();
out.println(team);
You'd need something like:
String first = team.substring(0,1).toUpperCase();
String rest = team.substring(1,team.length()).toLowerCase();
out.println(first + rest);
Similar as #DNA suggested but that will throw Exception if String length is 1. So added a check for same.
String output = team.substring(0,1).toUpperCase();
// if team length is >1 then only put 2nd part
if (team.length()>1) {
output = output+ team.substring(1,team.length()).toLowerCase();
}
out.println(i + "," + output);

Inserting Newline character before every number occurring in a string?

I have String of format something like this
String VIA = "1.NEW DELHI 2. Lucknow 3. Agra";
I want to insert a newline character before every digit occurring succeeded a dot so that it final string is like this
String VIA = "1.NEW DELHI " +"\n"+"2. Lucknow " +"\n"+"3. Agra";
How can I do it. I read Stringbuilder and String spilt, but now I am confused.
Something like:
StringBuilder builder = new StringBuilder();
String[] splits = VIA.split("\d+\.+");
for(String split : splits){
builder.append(split).append("\n");
}
String output = builder.toString().trim();
The safest way here to do that would be go in a for loop and check if the char is a isDigit() and then adding a '\n' before adding it to the return String. Please note, I am not sure if you want to put a '\n' before the first digit.
String temp = "";
for(int i=0; i<VIA.length(); i++) {
if(Character.isDigit(VIA.charAt(i)))
temp += "\n" + VIA.charAt(i);
} else {
temp += VIA.charAt(i);
}
}
VIA = temp;
//just use i=1 here of you want to skip the first charachter or better do a boolean check for first digit.

Categories

Resources