removing all character from string except a-z in array - java

i am trying to read words from the text file and store it in array.Problem from the code i tried as shown below is that it reads all characters such as "words," and "read." but i only want "words" and "read" in an array.
public String[] openFile() throws IOException
{
int noOfWords=0;
Scanner sc2 = new Scanner(new File(path));
while(sc2.hasNext())
{
noOfWords++;
sc2.next();
}
Scanner sc3 = new Scanner(new File(path));
String bagOfWords[] = new String[noOfWords];
for(int i = 0;i<noOfWords;i++)
{
bagOfWords[i] =sc3.next();
}
sc3.close();
sc2.close();
return bagOfWords;
}

Use regex replace :
replaceAll("([^a-zA-Z]+)","");
And apply that line to
bagOfWords[i] = sc3.next().replaceAll("([^a-zA-Z]+)","");

Use this code:
for (int i = 0; i < noOfWords; i++) {
bagOfWords[i] = sc3.next().replaceAll("[^A-Za-z0-9 ]", "");
}

You probably want only letters. In this case, you can use Character.isLetter(char) method.
Snippet:
String token = "word1";
String newToken = "";
for (int i = 0; i < token.length(); i++) {
char c = token.charAt(i);
if(java.lang.Character.isLetter(c)){
newToken += c;
}
}
System.out.println(newToken);

Related

Replacing a particular number - For Loop

I have the following code:
List<String> l1_0 = new ArrayList<String>(), l2_0 = new ArrayList<String>(),.....;
List<Integer> l1_1 = new ArrayList<Integer>(), l2_1 = new ArrayList<Integer>()......;
int lines1 = 0, lines2 = 0, lines3 = 0 .....;
Scanner s1 = new Scanner(new FileReader("file/path//t1.txt"));
while (s1.hasNext()) {
l1_0.add(s1.next());
l1_1.add(s1.nextInt());
lines1++;
}
s1.close();
func1(l1_0,l1_1,lines);
I have to perform same operation for 40 files.
Can we create a for loop to achieve it?
I am thinking of something along the lines of.
for (int i=1; i<= 40 ; i++)
{
Scanner s[i] = new Scanner(new FileReader("file/path//t[i].txt"));
while (s[i].hasNext()) {
l[i]_0.add(s[i].next());
l[i]_1.add(s[i].nextInt());
lines[i]++;
}
s[i].close();
func1(l[i]_0,l[i]_1,lines[i]);
}
If I understood correctly, you want to loop over your data 40 times. Once for each file.
for (int i=0; i< 40 ; i++)
{
// Initializers for this one file
List<String> strings = new ArrayList<>();
List<Integer> nums = new ArrayList<>();
int lineCount = 0;
String filename = "t" + i;
try (Scanner s = new Scanner(new FileReader("file/path/" + filename + ".txt"))) {
while (s.hasNext()) {
strings.add(s.next());
if (s.hasNextInt()) {
nums.add(s.nextInt());
}
lineCount++;
}
}
func1(strings,nums,lineCount);
}
for (int i=1; i<= 40 ; i++){
Scanner s[i] = new Scanner(new FileReader("file/path//t[i].txt"));
}
In java there is no implicit String pattern resolution. That means you have to create yourself, the String representing new file names like this:
"file/path//t" + i + ".txt"
Or you may use String.format():
String.format("file/path//t%d.txt",i)

How to read integers from a file that are separated with semi colon?

So in my codes, I am trying to read a file that is like:
100
22
123;22
123 342;432
but when it outputs it would include the ";" ( ex. 100,22,123;22,123,342;432} ).
I am trying to make the file into an array ( ex. {100,22,123,22,123...} ).
Is there a way to read the file, but ignore the semicolons?
Thanks!
public static void main(String args [])
{
String[] inFile = readFiles("ElevatorConfig.txt");
for ( int i = 0; i <inFile.length; i = i + 1)
{
System.out.println(inFile[i]);
}
System.out.println(Arrays.toString(inFile));
}
public static String[] readFiles(String file)
{
int ctr = 0;
try{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()){
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
words[i] = s2.next();
}
return words;
}
catch(FileNotFoundException e)
{
return null;
}
}
public static String[] readFiles(String file)
{
int ctr = 0;
try{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()){
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
words[i] = s2.next();
}
return words;
}
catch(FileNotFoundException e)
{
return null;
}
}
Replace this by
public static String[] readFiles(String file) {
List<String> retList = new ArrayList<String>();
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
String temp = s2.next();
String[] tempArr = se.split(";");
for(int k=0;k<tempArr.length;k++) {
retList.add(tempArr[k]);
}
}
return (String[]) retList.toArray();
}
Use regex. Read the entire file into a String (read each token as a String and append a blank space after each token in the String) and then split it at blank spaces and semi colons.
String x <--- contains all contents of the file
String[] words = x.split("[\\s\\;]+");
The contents of words[] are:
"100", "22", "123", "22", "123", "342", "432"
Remember to parse them to int before using as numbers.
Simple way to use BufferedReader Read line by line then split by ;
public static String[] readFiles(String file)
{
BufferedReader br = new BufferedReader(new FileReader(file)))
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String allfilestring = sb.toString();
String[] array = allfilestring.split(";");
return array;
}
You can use split() to split the string into array according to your requirement using regex.
String s; // string you have read from the file
String[] s1 = s.split(" |;"); // s1 contains the strings separated by space and ";"
Hope it helps
Keep the code for counting the size of the array.
I would just change the way you input your values.
for (int i = 0; i < ctr; i++) {
words[i] = "" + s1.nextInt();
}
Another option is to replace all non digit characters in your complete file string with a space. That way any non number character is ignored.
BufferedReader br = new BufferedReader(new FileReader(file)))
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String str = sb.toString();
str = str.replaceAll("\\D+"," ");
Now you have a string with numbers separated by spaces, we can tokenize them into number strings.
String[] final = str.split("\\s+");
then convert to int datatypes.

Swap the word in the String

input:-
1
Ans kot
Output:-
kot Ans
INPUT :
the first line of the input contains the number of test cases. Each test case consists of a single line containing the string.
OUTPUT :
output the string with the words swapped as stated above.**
Code:-
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
StringBuffer result = new StringBuffer();
for (int i = 0; i < a; i++) {
String b = sc.next();
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
}
What is wrong in my code ? above is code which i am trying.
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
this snippet of your code is only gonna reverse the sentence "word by word" not "character by character". therefore, you need reverse the string (my[j]) before you append it into the StringBuffer
Use this
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
sc.nextLine();
StringBuffer result = new StringBuffer();
for (int i = 0; i < a; i++) {
String b = sc.nextLine();
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
}
Multiple things:
You are using next api which will just read your string that you type word by word and you loop until a i.e. in your example just once. So instead use nextLine api which will read whole line instead of just a word and then split by space:
String b = sc.nextLine();
You are reading input with nextInt api followed by enter, you you might sometime end up having return character when reading next token using next api. Instead use:
int a = Integer.parseInt(sc.nextLine());
You are using StringBuffer which has an overhead of obtaining mutex and hence should use StringBuilder.
Takes String input and return String in reverse order of each characters.
String reverse(String x) {
int i = x.length() - 1;
StringBuilder y = new StringBuilder();
while (i >= 0) {
y.append(x.charAt(i));
i--;
}
return y.toString();
}
public static String reverseWords(String input) {
Deque<String> words = new ArrayDeque<>();
for (String word: input.split(" ")) {
if (!word.isEmpty()) {
words.addFirst(word);
}
}
StringBuilder result = new StringBuilder();
while (!words.isEmpty()) {
result.append(words.removeFirst());
if (!words.isEmpty()) {
result.append(" ");
}
}
return result.toString();
}
You can run this code:
String[] splitted = yourString.split(" ");
for (int i = splitted.length-1; i>=0; i--){
System.out.println(splitted[i]);
}
Code:-
Scanner sc =new Scanner(System.in);
int a =Integer.parseInt(sc.nextLine());
StringBuffer result= new StringBuffer();
for (int i = 0; i <a; i++) {
String b=sc.nextLine();
String my[]= b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length-1; j >0; j--) {
r.append(my[j]+" ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
enter code here

How to get the nextInt after the nextInt but retain the value

My problem is instead of the fixed value of iValueNext, I want the next value on the excel sheet to run, which is 125,152,...
import java.util.*;
import java.io.*;
public class ConvertingData
{
public static void main (String [] args)
{
int i=1;
int j;
int iValue;
int iValueNext;
try
{
Scanner ifsInput = new Scanner(new File("input.csv"));
PrintStream ifsOutput = new PrintStream(new File("output.csv"));
while(ifsInput.hasNextLine())
{
String tokens[] = ifsInput.nextLine().split(",");
String Repeat = tokens[tokens.length - 1];
String Value = tokens[tokens.length - 3];
iValue = Integer.parseInt( Value );
for (i=iValue;i<=iValueNext;i++)
{
System.out.println(i+","+Repeat);
ifsOutput.println(i+","+Repeat);
}
}
ifsInput.close();
ifsOutput.close();
}
catch (FileNotFoundException sMsg)
{
System.out.println("File not found");
}
}
}
Here is part of the csv file:
89,31,31
125,1,32
152,-12,20
155,1,21
181,6,27
287,1,28
290,1,29
308,-8,21
If you need to "peek" at the next line while processing the current line, first read all the lines in:
List<String> lines = new ArrayList<String>();
while(ifsInput.hasNextLine()) {
lines.add(ifsInput.nextLine());
}
ifsInput.close();
then process the lines one by one with access to the next line:
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
String nextLine = i < lines.size() - 1 ? null : lines.get(i + 1);
String tokens[] = line.split(",");
String nextTokens[] = nextLine.split(",");
// whatever logic you need
ifsOutput.close();
}

Taking an Input from a file

This is the content of my Input file:
0110000000000000000000000000000000000000
I want to take this input to an int[], but BufferReader gives me a char[]. How do I get an int[] from it?
This is my code:
BufferedReader br = new BufferedReader(new FileReader("yes.txt")); // will give a char array not int
int[] input;
input[0] = 0;
input[1] = 1;
input[1] = 1;
// and so on
Solution:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
for (int i = 0; i < s.length; i++) {
int integer = (int) Character.getNumericValue(char_array[i]);
System.out.println(integer);
}
You can use the Character class to convert a char array to an int.

Categories

Resources