I'm trying to split some input code from a file a certain way and am completely lost on how to do it. I have the file reading incorrectly. I'm just not sure how to split it the way I want it. I currently have it set up like this (below) and it works fine I'm just wondering if there's a way to split it again or something, the lines from the file look as followed:
"Y8 T L6 L2 T Y3" the numbers or letters could vary, and might or might not have a number, I would set it up so I can have every character and number separated into their own String[], how can I do this? the way I have it set up now takes the number along with the character and I don't want that as I need access to the numerical values, thanks.
Code
{
File file = new File(FileName);
Scanner scanner = new Scanner(file);
String currentLine = scanner.nextLine();
String[] seperated = currentLine.split(" ");
}
You can indeed continue with what you have. Since you've read everything in and separated it into a String array, you can loop over the elements in the array and check to see if they have a number following them. The code I'm going to post assumes that each input is either 1) a single letter or 2) a single letter followed by a single number:
for (String temp : seperated) {
int numberIWant;
if (temp.length() == 2) {
numberIWant = temp.charAt(1);
}
//Do something with this number, if you need the letter as well
//Use temp.charAt(0)
If your interest is just having the two separate arrays, then you may not need to split. Just remove the white space and separate the numbers from the other characters.
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String[] args) {
String currentLine = "Y8 T L6 L2 T Y3";
//Remove the spaces
String withoutSpaces = currentLine.replace(" ", "");
String[] characters = withoutSpaces.split("");
List<Integer> numeric = new ArrayList<>();
List<String> character = new ArrayList<>();
for (String each : characters) {
if (isNum(each)) {
numeric.add(Integer.parseInt(each));
} else {
character.add(each);
}
}
Integer[] numarray = numeric.toArray(new Integer[numeric.size()]);
String[] chararray = character.toArray(new String[character.size()]);
for(Integer num: numarray){
System.out.println(num);
}
for(String charac: chararray){
System.out.println(charac);
}
}
public static boolean isNum(String strNum) {
boolean ret = true;
try {
Double.parseDouble(strNum);
} catch (NumberFormatException e) {
ret = false;
}
return ret;
}
}
Related
The code here only shows how many words they are, how do i ignore the words that are the same?
For example, "A long long time ago, I
can still remember", would return 8 instead of 9.
I want it to be a method which takes one parameter s of
type String and returns an int value. And im only allowed to use the bacics, so no hash keys or hash set and advance stuff.
public static int mostCommonLetter(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
}
How do i ignore the words that are the same?
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String input = "A long long time ago, I can still remember";
String[] words = input.split(" ");
List<String> uniqueWords = new ArrayList<>();
for (String word : words) {
if (!uniqueWords.contains(word)) {
uniqueWords.add(word);
}
}
System.out.println("Number of unique words: " + uniqueWords.size());
}
}
Output: Number of unique words: 8
Basically, what you can do if you're allowed to use data structures like lists and so on, is create a list and put the words of the input sentence in the list if and only if they aren't already there.
General idea:
public int getUniqueWords(String input) {
// Split the string into words using the split() method
String[] words = input.split(" ");
// Create a Set to store the unique words
Set<String> uniqueWords = new HashSet<String>();
// Loop through the words and add them to the Set
for (String word : words) {
uniqueWords.add(word);
}
// Return unique words amount
return uniqueWords.size();
}
Same solution using StreamAPI:
public int getUniqueWords2(String input) {
// here we can safely cast to int, because String can contain at most "max int" chars
return (int) Arrays.stream(input.split(" ")).distinct().count();
}
If it is needed to handle multiple spaces between words, add some cleanup for input:
// remove leading and trailing spaces
cleanInput = input.trim();
// replace multiple spaces with a single space
cleanInput = cleanInput.replaceAll("\\s+", " ");
Considering the requirement "allowed to use the bacics":
hashtable (HashSet) is a basic data structure in algorithms
problem of counting unique items cannot be logically solved without a container holding "aready seen" items, so algorithm could check whether the next item is counted or not
in the role of container in the simplest case could be a list, but that would cause O(n^2) time complexity.
You can use a Set<T> collection type, that can only contains unique values:
public static int getTotalUniqueWords(String input) {
String[] words = input.split(" ");
Set<String> uniqueWords = new HashSet<>();
Collections.addAll(uniqueWords, words);
return uniqueWords.size();
}
or with Streams:
public static long getTotalUniqueWordsStream(String input) {
String[] words = input.split(" ");
return Arrays.stream(words).distinct().count();
}
So I have been trying to get a user inputted string to have a newline every n amount of characters. What I have found is a basically what I have written, I am pretty new to Java(Python has a function to .fill but I cant figure this out in Java) and cant seem to get my string to not break words apart. I set the program to "\n" every 10 characters but then it breaks some words right in the middle... I want it to take that word and move it to the next line if it will not fit into the 10 character limit.
import java.util.Scanner;
public class Wrap {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your text: ");
String newString = scan.nextLine();
newString = newString.replaceAll(".{10}", "$0\n");
System.out.println(newString);
/** Second Method, still cuts the words off...
StringBuilder builtString = new StringBuilder();
int i = 0;
while ((i= builtString.indexOf(newString, i + 10)) != -1) {
builtString.replace(i, i+1, "\n");
}
System.out.println(builtString);
*/
System.out.println(newString);
}
}
Words are broken apart :(
Output:
This is a
test and i
t doesnt s
eem to be
working pr
operly.
In Python I got this output which was what I wanted, but Java doesn't seem to have a textwrap function that's "easy" like Python's or at least I haven't figured it out yet.
Desired Output
public static void main(String[] args) {
String text = "This is a test and it doesnt seem to be working properly.";
String[] works = text.split(" "); // get list of works
StringBuilder line = new StringBuilder();
StringBuilder result = new StringBuilder();
for (String work : works) {
if (line.length() + work.length() > 10) { //add line to result if it full
result.append(line).append("\n");
line = new StringBuilder(); //reset line is empty
}
line.append(work).append(" ");
}
result.append(line);
System.out.println(result.toString());
}
How Would we write a program using Java to read a paragraph from the user and replace specific words mentioned in a vector to the following format, i.e.,
For example word Happy is reduced to H****.
Any Help will be Appriciated.
import java.io.*;
import java.util.*;
class replaceString {
public static String putStars(String str) {
char first_char = str.charAt(0);
String ans = new String();
ans = String.valueOf(first_char);
for(int i = 1;i < str.length(); ++i ) {
ans = ans + "*";
}
return ans;
}
public static String replaceWords(String str, Vector<String> v1) {
String[] words = str.split("\\W+"); //split across all types of punctuation
String ansString = new String();
for(String to_be_replaced : words) {
boolean found = false;
for(String to_replace_with : v1) {
if(to_be_replaced.equals(to_replace_with)) {
//System.out.println("in");
ansString = ansString +putStars(to_be_replaced) + " ";
found = true;
}
}
if(found == false) {
ansString = ansString + to_be_replaced + " ";
}
}
return ansString;
}
public static String replaceWords1(String str, Vector<String> v1) {
for(String currStr : v1) {
str.replace(str, );
}
return ansString;
}
public static void main(String args[])throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the paragraph that you would like to edit ");
String s = br.readLine();
// Let us assume some strings in our very own vector
Vector<String> v1 = new Vector<String>();
v1.addElement("Hello");
v1.addElement("Hi");
v1.addElement("Heya");
v1.addElement("Howdy");
v1.addElement("Howu");
String ans = replaceWords(s, v1);
System.out.println("Paragraph after replacement becomes\n\n"+ ans);
}
}
this is my current code but its not working fine
There could be other possibilities, but here's an example I did based on this answer:
We need all the words we need / want to match, and store them in an array:
String [] words = {"appy", "eya", "dy"};
(Optional) If you really need a Vector, I suggest to create a List (ArrayList) instead, and we can do it this way:
List <String> wordsToReplace = Arrays.asList(words);
Otherwise just modify the method in the next step to receive an array...
We create a function that receives this List and the phrase we want to check for and that returns the new String with the replaced text in it
So, our whole code ends up like this:
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordReplacer {
public static void main(String[] args) {
String [] words = {"appy", "eya", "dy"};
List <String> wordsToReplace = Arrays.asList(words);
System.out.println(replaceWords("Happy", wordsToReplace));
System.out.println(replaceWords("Heya", wordsToReplace));
System.out.println(replaceWords("Howdy?", wordsToReplace));
System.out.println(replaceWords("Howdy? My friend lives in Pompeya and every time I see her I say \"Heya\" to her, she is very happy", wordsToReplace));
}
private static String replaceWords(String word, List <String> wordsToReplace) {
for (String s : wordsToReplace) {
Pattern p = Pattern.compile(s, Pattern.CASE_INSENSITIVE); //We create a pattern that matches each word in our list. (1)
Matcher m = p.matcher(word); //We actually check for each match against our phrase
StringBuilder sb = new StringBuilder();
if (m.find()) { //If there was a match, we're going to replace each character for an '*' (2)
for (int i = 0; i < s.length(); i++) {
sb.append("*");
}
}
word = m.replaceAll(sb.toString()); //We replace each match with '*' (3)
}
return word; //We return the modified word
}
}
I'm going to explain what each comment (1), (2), (3) do in a better and simpler way:
(1) As shown in the linked answer, they use \b regex command to match whole words, but in this case we're using it to match parts of words, not whole words, so we don't need it here...
(2) Only if we found a match we fill the StringBuilder with * characters... If we didn't do it this way, we would be getting: H* instead of H**** for the case of Happy word, this way we ensure we get the correct amount of * for every word in the List.
(3) We replace the matches for the total number of * in the StringBuilder so we get the correct output.
The program above produces the following output:
H****
H***
How**?
How**? My friend lives in Pomp*** and every time I see her I say "H***" to her, she is very h****
Try something like that with a map that contains yours replacing rules :
String input; //input string
Map<String,String> mapReplace = new HashMap<String,String>();
mapReplace.put("Hello","H****");
Iterator<String> keys = mapReplace.keySet().iterator();
while(keys.hasNext()){
String key = keys.next();
input = input.replace(input, mapReplace.get(key));
}
I am having difficulty in the following, replacing certain characters from the string
There will be two inputs, first will be character and second will be string
then I need to replace all those characters from the string with it's position
for example ,
the input and output of my program are as follows which is absolutely correct as per the requirement
Input : i this is Ignite
( Here "i" is the first input and "this is Ignite" is the second input
Output : th2s 5s 8gn11te
Input : i this is ignite and i am pratik
Output : th2s 5s 8gn11te and 20 am prat30k
The replacement should not be case-sensitive.
I had written the following program but it's having some bugs, Bugs in the sense that I am actually doing some project online and the automated sytem is not accepting the program because of some logical error.The automated system does some test cases with different inputs and check the output ( not exceptions or invalid inputs) can someone help me identify it ?
import java.util.*;
import java.io.*;
class rplc
{
public static void main(String args[])
{
String str,temp="";
char ch, ch2;
int arr[]=new int[100];
int len,i,x=0;
Scanner input=new Scanner(System.in);
ch=input.next().charAt(0);
str=input.nextLine();
str=str.replaceAll("^\\s+","");
ch2=ch;
if(Character.isUpperCase(ch))
ch2=Character.toLowerCase(ch);
else if(Character.isLowerCase(ch))
ch2=Character.toUpperCase(ch);
len=str.length();
temp=str;
for(i=0;i<len;i++)
{
if(str.charAt(i)==(int)ch || str.charAt(i)==(int)ch2)
{
arr[x]=i;
x=x+1;
}
}
x=0;
for(i=0;i<len;i++)
{
if(str.charAt(i)==(int)ch || str.charAt(i)==(int)ch2)
{
temp=str.substring(0,i);
temp=temp+(arr[x]);
temp=temp+str.substring(i+1,len);
str=temp;
len=temp.length();
x=x+1;
}
}
System.out.print(temp);
}
}
Seems like your code should work. Just in case I tried writing a simpler program:
Scanner input=new Scanner(System.in);
char ch = Character.toLowerCase(input.next().charAt(0));
String str = input.nextLine().trim().toLowerCase();
input.close();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < str .length(); i++) {
if (str.charAt(i) == ch) {
buf.append(i);
}
else {
buf.append(str.charAt(i));
}
}
System.out.println(buf.toString());
And the output seems to be same.
Perhaps your function should return the value instead of printing it?
From the comments I understand that there will be only 1 input from the user.
The following input:
i this is ignite and i am pratik
Where the first 'i' is the charcter which needs to be replaced in 'this is ignite and i am pratik'.
Modify following:
str=input.nextLine();
str=str.replaceAll("^\\s+","");
to
str = input.nextLine();
str = str.substring(1);
str = str.replaceAll("^\\s+", "");
Try Something like this,
Scanner s = new Scanner(System.in);
String Line = s.nextLine();
String ch = Line.substring(0,Line.indexOf(" ")).trim();
Line = Line.substring(Line.indexOf(" ")).trim();
String[] x= Line.split(ch);
String y="";
for(String t:x){
y=y.equals("")?t:y+y.length()+t;
}
System.out.println(y);
I did some code cleaning but the most important steps were to use a list of dynamic size instead of a fixed size array and a while-loop with dynamic termination instead of a for-loop. This is because the length of the output String will change (increase) when there a characters to be replaced at positions >9 and thus in your code the execution can stop in the middle of the result string and there are characters not being replaced.
There is even a special case, when the replaced character is a number itself. To avoid problems there I added this line
i = i + Integer.toString(list.get(pos)).length()-1;
in order to step over newly added number characters in the output String.
import java.util.*;
import java.io.*;
class rplc
{
public static void main(String args[])
{
List<Integer> list = new ArrayList<Integer>();
Scanner input=new Scanner(System.in);
char ch = input.next().charAt(0);
String str=input.nextLine().trim();
int len=str.length();
for(int i=0;i<len;i++)
{
if(str.charAt(i)==Character.toLowerCase(ch) || str.charAt(i)==Character.toUpperCase(ch))
{
list.add(i);
}
}
int pos = 0;
int i = 0;
while(i<str.length())
{
if(str.charAt(i)==Character.toLowerCase(ch) || str.charAt(i)==Character.toUpperCase(ch))
{
String start = str.substring(0,i)+Integer.toString(list.get(pos));
String end = i<=str.length() ? str.substring(i+1) : "";
i = i + Integer.toString(list.get(pos)).length()-1;
pos++;
str = start.concat(end);
}
i++;
}
System.out.print(str);
}
}
I can't see any special bugs. Could be that I lost sight of something. This is my first answer here and English is not my mother tongue, so please excuse any formal errors.
I liked the problem so I made my own answer. apologies for the dirty looking code. :)
Scanner input=new Scanner(System.in);
String firstInput=input.nextLine().charAt(0) + "";
//ensure its lower case
firstInput=firstInput.toLowerCase();
String secondInput=input.nextLine();
//ensure char in secondInput is lower cased too.
secondInput=secondInput.replaceAll(firstInput.toUpperCase(),firstInput);
String[] splitted=secondInput.split(firstInput);
String output="";
int current=0;
for(int i=0;i<splitted.length;i++){
String s=splitted[i];
current=current+ s.length();
if(i==splitted.length-1){
output=output+s;
}else{
output=output+s;
output=output+ current;
current++;
}
}
//edited part, as split doesn't split if firstinput is the last character of the string
if(secondInput.endsWith(firstInput)){
output=output+secondInput.length();
}
System.out.println(output);
Is there a library that can help me split a String to integers by delimiters and range marks?
for instance
values="32,38,42-48,84"
output:
int[] = 32,38,42,43,44,45,46,47,48,84
You can use builtin java functions of string class like split and contains to achieve it. In order to convert string to int use Integer.parseInt. E.g.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SimpleParser {
public static void main(String[] args) {
String input = "32,38,42-48,84";
String[] chunks = input.split(",");
System.out.println(Arrays.toString(chunks));
List<Integer> ints = new ArrayList<>();
for (String chunk : chunks) {
if (chunk.contains("-")) {
String[] rangeChunks = chunk.split("-");
if (rangeChunks.length != 2) {
throw new IllegalArgumentException("Invalid range");
}
for (int i = Integer.parseInt(rangeChunks[0]); i <= Integer.parseInt(rangeChunks[1]) ; i++) {
ints.add(i);
}
}else {
ints.add(Integer.parseInt(chunk));
}
}
System.out.println(ints);
}
}
Outputs
[32, 38, 42, 43, 44, 45, 46, 47, 48, 84]
If what you want is to get the whole range (From 42-55 for example), then I'm not entirely sure, but you can always use Regular Expressions to find everything that's not a number . The expression could be "[^0-9] Then use replace and change by some character (e.g commas). Then just split by commas. Feel free to read more about this here: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html (NOTE: I'm not related in any way to Vogella. I just liked the tuto :)
EDIT:
I can now see the output you want (which I believe wasn't there). If that's what you want, then find all split by commas first. After, check if you have elements in which you have a symbol (- for example), and if so, then split by it and use the numbers to create the range. Here's an example of a working code:
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
String[] splitted = s.split(",");
for(int i = 0; i < splitted.length;i++){
if(splitted[i].contains("-")){
String[] nums = splitted[i].split("-");
int from = Integer.parseInt(nums[0]);
int to = Integer.parseInt(nums[1]);
for(int j = from;j <= to;j++)
System.out.print(j+",");
}
else
System.out.print(splitted[i] + ",");
}
Might not be the most efficient solution, but it works.
Get the individual items
//Creates an array of numbers (e.g. "32") and ranges (e.g. "42-48")
String[] items = String.split(",");
Loop through the array and split into ranges if range mark exists
if (items[i].contains("-")
{
//creates an array of two containing the start and end of range
String[] ranges = items[i].split("-");
}
Then for each String you have in your arrays, parse out the Integer
Integer parsedInt = Integer.parseInt(item[i]);
Lastly, convert and add the items to a collection like ArrayList then convert the ranges and loop through the range (42-48), adding the numbers to the collection as well.
I have used simple String arrays ans array list for the solution:
String[] values_s = items.split(",")
List<Integer> values_i = new ArrayList<Integer>();
for(String s: values_s){
if ( s.contains('-') ){
int sum = 0;
String[] g = s.split("-");
for (int i=Integer.parseInt(g[0]); i<Integer.parseInt(g[g.length-1]); i++)
values_i.add(i);
} else {
values_i.add(Integer.parseInt(s));
}
}
int[] n = (int[])values_i.toArray(int[values_i.size()]);
That should do it.