Swap the word in the String - java

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

Related

Split lines with "," and do a trim on every element [duplicate]

This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:
73
56
30
75
80
ect..
What I want is to be able to read multiple lines that are structured like this:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
I just want to essentially import each line as an array, while structuring them like an array in the text file.
Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
I provide my code here.
public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}
public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}
The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.
try {
String line = "";
int rowNumber = 0;
while(scan.hasNextLine()) {
line = scan.nextLine();
String[] elements = line.split(',');
int elementCount = 0;
for(String element : elements) {
int elementValue = Integer.parseInt(element);
spaces[rowNumber][elementCount] = elementValue;
elementCount++;
}
rowNumber++;
}
} // you know what goes afterwards
Since it is a file which is read line by line, read each line using a delimiter ",".
So Here you just create a new scanner object passing each line using delimter ","
Code looks like this, in first for loop
for(int i = 0; i < 10; i++)
{
Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = newScan.nextInt();
}
}
Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character.
As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.
Example:
scan.useDelimiter(",|\\r\\n");
This sets the delimiter to both "," and carriage return + new line characters.
Why use a scanner for a file? You already have a BufferedReader:
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
Now you can read the file line by line. The tricky bit is you want an array of int
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
String[] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
spaces[row][i] = Integer.parseInt(array[i]);
}
row++;
}
The other approach is using a Scanner for the individual lines:
while ((line = reader.readLine()) != null)
{
Scanner s = new Scanner(line).useDelimiter(',');
int col = 0;
while (s.hasNextInt())
{
spaces[row][col] = s.nextInt();
col++;
}
row++;
}
The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.

How to remove stop words in Java

I am trying to find top k words in a "data" text file. But I cannot remove stopwords including in "stop.txt" should I do it manually adding stopwords one by one or there is a method to read stop.txt file and remove these words in data.txt file?
try {
System.out.println("Enter value of 'k' words:: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
w = new String[n];
r = new int[n];
Set<String> stopWords = new LinkedHashSet<String>();
BufferedReader SW = new BufferedReader(new FileReader("stop.txt"));
for(String line; (line = SW.readLine()) != null;)
stopWords.add(line.trim());
SW.close();
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
String text = "";
String sz = null;
while((sz=br.readLine())!=null){
text = text.concat(sz);
}
String[] words = text.split(" ");
String[] uniqueLabels;
int count = 0;
uniqueLabels = getUniqLabels(words);
for(int j=0; j<n; j++){
r[j] = 0;
}
for(String l: uniqueLabels)
{
if("".equals(l) || null == l)
{
break;
}
for(String s : words)
{
if(l.equals(s))
{
count++;
}
}
for(int i=0; i<n; i++){
if(count>r[i]){
r[i] = count;
w[i] = l;
break;
}
}
count=0;
}
display(n);
} catch (Exception e) {
System.err.println("ERR "+e.getMessage());
}
Read file contents by:
List<String> stopwords = Files.readAllLines(Paths.get("english_stopwords.txt"));
Then use this for removing stop words:
ArrayList<String> allWords =
Stream.of(original.toLowerCase().split(" "))
.collect(Collectors.toCollection(ArrayList<String>::new));
allWords.removeAll(stopwords);
String result = allWords.stream().collect(Collectors.joining(" "));
Removing Stopwords from a String in Java

Subsequence words

Suppose this is my .txt file ABCDBCD and I want to use .substring to get this:
ABC BCD CDB DBC BCD
How can I achieve this? I also need to stop the program if a line is shorter than 3 characters.
static void lesFil(String fil, subsekvens allHashMapSubsequences) throws FileNotFoundException{
Scanner scanner = new Scanner(new File("File1.txt"));
String currentLine, subString;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
for (int i = 0; i + subSize <= currentLine.length(); i++){
subString = currentLinje.substring(i, i + subSize);
subSekStr.putIfAbsent(subString, new subsequence(subString));
}
}
scanner.close();
With a minor changes of your code:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("C:\\Users\\Public\\File1.txt"));
String currentLine, subString;
int subSize = 3;
while (scanner.hasNextLine()) {
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
if (currentLine.length() < subSize) {
break;
}
for (int i = 0; i + subSize <= currentLine.length(); i++) {
subString = currentLine.substring(i, i + subSize);
System.out.print(subString + " ");
}
System.out.print("\n");
}
scanner.close();
}
This may be what you need
String str = "ABCDBCD";
int substringSize = 3;
String substring;
for(int i=0; i<str.length()-substringSize+1; i++){
substring = str.substring(i, i+substringSize);
System.out.println(substring);
}
import java.util.*;
public class Main
{
public static void main(String[] args) {
String input = "ABCDBCD";
for(int i = 0 ; i < input.length() ; i++) {
if(i < input.length() - 2) {
String temp = input.substring(i,i+3);
System.out.println(temp);
}
}
}
}

Java. Reading 2 Dimensional array in a file (notepad)

example i have this numbers or arrays on my file (notepad)
2 3 4 5 7 2 6 2
2 4 6 8 9 4 8 1
I want to ask if how to read the next row. I can only read the first row using this code.
String path = "/path/notepad.txt";
String stringOfNumbers[];
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader (new FileReader(path));
String lineOfNumbers = br2.readLine();
stringOfNumbers = lineOfNumbers.split(" ");
//stringOfNumbers = lineOfNumbers.split("\n");
String str = lineOfNumbers.replace(","," ");
System.out.println(str);
System.out.print("");
int numbers[][] = new int [stringOfNumbers.length][stringOfNumbers.length];
for (int i = 0; i < numbers.length; i++)
{
numbers[i][i] = Integer.parseInt(stringOfNumbers[i]);
}
System.out.print("Enter the number to search: ");
int searchNumber = Integer.parseInt(br.readLine());
int location = 0;
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i][i] == searchNumber)
{
location = i+ 1;
}
}
thank you in advance.
I would do somethin like this
FileReader fr = new FileReader("myFileName");
BufferedReader br = new BufferedReader(fr);
while((line=br.readLine())!=null) // as long as there are lines in the file
{
stringOfNumbers = line.split(" ");
// other code
}
Following code will Help you save all numbers in a file to memory
Scanner scanner = new Scanner(path);
List<Integer[]> integerArList = new ArrayList<Integer[]>();
while(scanner.hasNextLine()){
String lineOfNumbers = scanner.nextLine();
stringOfNumbers = lineOfNumbers.split(" ");
//stringOfNumbers = lineOfNumbers.split("\n");
String str = lineOfNumbers.replace(","," ");
System.out.println(str);
System.out.print("");
Integer[] numbers = new Integer[stringOfNumbers.length];
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = Integer.parseInt(stringOfNumbers[i]);
}
integerArList.add(numbers);
}
After this you can search any Integer by traversing each array in the List like this:
int searchMe = <get this from user>
int location=0;
boolean found=false;
for(Integer[] intAr: integerArList){
for(int i=0;i<intAr.length;i++){
if(intAr[i]==searchMe){
location+=(i+1)
found=true;
break;
}
}
if(found) break;
location+=intAr.length;
}
System.out.println("Location of " + searchMe +" : " +(found?location:"Not Found in Data"));
Hope this helps.
To read all lines of a text file you can do something like this:
String path = "/path/notepad.txt";
String stringOfNumbers[];
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader (new FileReader(path));
ArrayList<String> listOfLines = new ArrayList<String>();
//String lineOfNumbers = "";
String line = "";
String allIndexes = "";
while ((line = br2.readLine()) != null) {
if(!line.isEmpty()){
listOfLines.add(line);
}
}
for(String lineOfNumbers : listOfLines){
stringOfNumbers = lineOfNumbers.split(" ");
//stringOfNumbers = lineOfNumbers.split("\n");
String str = lineOfNumbers.replace(","," ");
System.out.println(str);
System.out.print("");
int numbers[][] = new int [stringOfNumbers.length][listOfLines.size()];
for (int i = 0; i < numbers.length; i++)
{
numbers[i][listOfLines.indexOf(lineOfNumbers)] = Integer.parseInt(stringOfNumbers[i]);
}
System.out.print("Enter the number to search: ");
int searchNumber = Integer.parseInt(br.readLine());
int locationI = 0;
int locationJ = 0;
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < listOfLines.size(); j++)
if (numbers[i][j] == searchNumber)
{
locationI = i + 1;
locationJ = j + 1;
allIndexes += locationI + ":" + locationJ + " ";
}
}
}

Copying characters in a string

i am trying to delete every digit from a string and then copy the letter that comes after that digit.
So for example the string 4a2b should output aaaabb.
So far my code looks like this:
Scanner scan= new Scanner(System.in);
String s = scan.nextLine();
String newString = s.replace(" ", "");
newString=newString.replaceAll("\\W+", "");
newString=newString.replaceAll("\\d+", "");
System.out.println(newString);
Is it possible to use regex and replaceAll to do that?
Try,
String newString = "4a2b";
String num = "";
StringBuilder res = new StringBuilder();
for (int i = 0; i < newString.length(); i++) {
char ch = newString.charAt(i);
if (Character.isDigit(ch)) {
num += ch;
} else if (Character.isLetter(ch)) {
if (num.length() > 0) {
for (int j = 0; j < Integer.parseInt(num); j++) {
res.append(ch);
}
}
num="";
}
}
System.out.println(res);
Try this:
public static void main(String[] args)
{
String str = "ae4a2bca";
Matcher m = Pattern.compile("(\\d+)(.)").matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find())
{
m.appendReplacement(sb, times("$2", Integer.parseInt(m.group(1))));
}
m.appendTail(sb);
System.out.println(sb.toString());
}
private static String times(String string, int t)
{
String str = "";
for (int i = 0; i < t; ++i) str += string;
return str;
}

Categories

Resources