Prints String with white space in java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Am having a txt file. which is having line like
if(true) return true;
I need to get the sub string from preceding spaces that is
" if(true) "
and another sub string as
" retrun true; "
I am reading this line using scanner class and assign to a string. from that string am converting it into toCharArray. I have tried using toCharArray[] but the spaces are ignored. How to get the substring from the preceding spaces using toCharArray
kindly anybody help me to get a solution for this issue
Thanks in advance.

You can use StringReader:
String str = "Some String";
int numberOfChars = str.length();
StringReader sr = new StringReader(str);
char[] chars = new char[numberOfChars];
int i = 0, read = 0;
try {
while ((read = sr.read()) != -1) {
chars[i] = (char)read;
i++;
}
} catch (IOException e) {
// handle the exception
}
This will read all the characters, without skipping any of them.
EDIT:
Now that I understand what you are trying to do, I would recommend you to define a grammar for your instructions. In this way you should be able to identify these 2 separate statements or instructions. I would suggest you to use a compiler building tool for that like e.g. ANTLR.

I have found one solution by using Regular expression for this question. The answer is as follows
public class Test{
public static void main(String[] args){
String str = " TestProgram";
Pattern pattern = Pattern.compile("\\s*[a-zA-Z0-9]+$");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(0,matcher.end());
}
}
}
Thanks

Related

How do I split a string into sentences while maintaining all the spaces in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I tried the following regex:
sentences = sb.toString().split("(?<=[a-z])*\\.\\s*");
I am using a stringBuilder sb and converting it to string and then using a split function
The regex checks for 0 or more characters before '.' and 0 or more spaces after the '.'
However, it doesn't work for the following input
Hello World. Shipped to U.S on Friday.We are here .Good input
But I need to keep the space before We are here
Req Output
Hello World
Shipped to U.S on Friday
We are here
Good input
use this regex: ([^\.]+)(\.|$)*?
you can read about group matchers and see the full matches here : https://regex101.com/r/yV9GES/5
edit: updated the link for answer in the comment.
Split your string using \\. i.e. on .
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString("Hello World. We are here .Good input.".split("\\.")));
}
}
Output:
[Hello World, We are here , Good input]
Why do you have to use a RegEx?
You can simply use indexOf and substring
public List<String> splitOnDot(String input) {
List<String> result = new ArrayList<>();
int idx;
while ((idx = input.indexOf('.')) != -1) {
result.add(input.substring(0, idx));
input = input.substring(idx + 1);
}
return result;
}
Successful test:
#Test
public void test1() {
assertThat(splitOnDot("Hello World. We are here .Good input.")).contains("Hello World", " We are here ", "Good input");
}

How to extract email adresses from this string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
For example I have this string, where email addresses are differently formatted:
"a.b#c.d" <a.b#c.d>|"Michal pichal (michal.pichal#g.d)" <michal.pichal#g.d>|Melisko Pan <melisko.pan#domena.sk>
I need to extract the email addresses in a form of:
a.b#c.d|michal.pichal#g.d|melisko.pan#domena.sk
My idea was to get any char near # from group [0-9][A-Z][a-z]#.- but I do not know how. Please help with some hint.
This regex extracts emails out of your string:
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[\\w.]+#[\\w.]+");
Matcher matcher = pattern.matcher("\"a.b#c.d\" <a.b#c.d>|\"Michal pichal (michal.pichal#g.d)\" <michal.pichal#g.d>|Melisko Pan <melisko.pan#domena.sk>\r\n");
while(matcher.find()){
String group = matcher.group();
System.out.println("group="+group);
}
It prints:
group=a.b#c.d
group=a.b#c.d
group=michal.pichal#g.d
group=michal.pichal#g.d
group=melisko.pan#domena.sk
import java.util.Scanner;
class test{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String res = ""; //This holds the final result
for(int i=0; i<str.length(); ++i){ //Loop through the entire string
if(str.charAt(i)=='<'){
String build = "";
for(int j=i+1; j<str.length(); ++j){
if(str.charAt(j)=='>'){
break; //Break when we hit the '>'
}
build += str.charAt(j); //Add those between < and >
}
res += build + "|"; //Add the pipe at the end
}
continue;
}
System.out.println(res);
}
}
This ought to do it.
Just run simple nested loops. No need for regex.

separate too long words in string in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a String with some text, f.e.
"Thisisalongwordtest and I want tocutthelongword in pieces"
Now I want to cut the to longs word in 2 pieces with a blank. The word should be cut if it's longer than 10 characters.
The result should be:
"Thisisalon gwordtest and I want tocutthelo ngword in pieces"
How can I achieve this efficiently?
are you looking for this? or I misunderstood the question?
String newString = oldStr.replaceAll("\\w{10}","$0 "))
with your example, the newString is:
Thisisalon gwordtest and I want tocutthelo ngword in pieces
Edit for Pshemo's good comment
to avoid to add space after words with exact 10 chars:
str.replaceAll("\\w{10}(?=\\w)","$0 "));
.replaceAll("(\\w{10})(?=\\w)", "$1 ")
Tested with:
test("abcde fghij klmno pqrst");
test("abcdefghijklmnopqrst");
test("abcdefghijklmnopqrstuv");
test("abcdefghij klmnopqrstuv");
test("abcdefghij klmnopqrst uv");
separate text into words. (by space)
cut long words and replace source word with new words
assemble text again
Note, that this approach will kill multiple-spaces.
(?=\w{10,}\s)(\w{10})
Should be replaced by
"\1 "
you can use replace function.
If it has number or special characters
(?=\S{10,}\s)(\S{10})
can be used.
This is the code i wrote check it once.....
public class TakingInput {
public static void main(String[] args) {
String s="Thisisalongwordtest and I want tocutthelongword in pieces";
StringBuffer sb;
String arr[]=s.split(" ");
for(int i=0;i<arr.length;i++){
if(arr[i].length()>10){
sb=new StringBuffer(arr[i]);
sb.insert(10," ");
arr[i]=new String(sb);
}
}
for(String ss: arr){
System.out.println(ss);//o/p: "Thisisalon gwordtest and I want tocutthelo ngword in pieces"
}
}
}
This code will do exactly what you want.
First create a method that splits a String if its longer than 10 chars:
String splitIfLong(String s){
if(s.length() < 11) return s + " ";
else{
String result = "";
String temp = "";
for(int i = 0; i < s.length(); i++){
temp += s.charAt(i);
if(i == 9)
temp += " ";
result += temp;
temp = "";
}
return result + " ";
}
}
Then use Scanner to read every word in the sentence seperated by a white space" ":
String s = "Thisisalongwordtest and I want tocutthelongword in pieces";
String afterSplit = "";
Scanner in = new Scanner(s);
Then call the splitIfLong() method for every word in the sentence. And add what the method returns to a new String:
while(in.hasNext())
afterSplit += splitIfLong(in.next());
Now you can use the new String as you wish. If you call:
System.out.println(afterSplit);
it will print:
Thisisalon gwordtest and I want tocutthelo ngword in pieces
Hope this helps

linear search for a given string in java ? Are there any better solutions? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Sorry if my question is silly but I need some help.
Well, the problem is that I am trying to learn java and was trying to make a little program
that will search through the text file for a matching string that has been inserted in the
parameter. I wanted to know which part of the program should I fix to make the method work properly or at least want to know if there is a better solution.
public String linaerSearch(String filename,String strToArrays){
String[]arrays;
File f = new File("C:\\Users\\toyman\\Documents\\NetBeansProjects\\ToyMaker\\"+filename);
String[]items = (strToArrays.split("\\s*,\\s*"));//converting the string into arrays by comma
//convert the int into string
StringBuilder build = new StringBuilder();
if(f.exists()){ //checks if the file actually exists
try(FileInputStream fis = new FileInputStream(f)){
int con; int incrementor =0;
while((con=fis.read())!=-1){
incrementor++;
char str = (char)con;
String str2 = Character.toString(str);
if(items[ ????? ].equals(str2)){
// I want to check if the string that has been passed in the parameter
// exists in the file. But I got confused at the items[ ???? ].
System.out.println("found you");
}
//System.out.println();
//convert to char and display it
System.out.print(str2);
}
}catch(Exception e){
e.printStackTrace();
}
}else{
System.out.println("The file doesn't exist. Create a new file or use a existing file");
}
return "";
}
If you want to search for some string in a text, and do it properly, it has nothing to do with Java. What you're looking for is a string searching algorithm.
Try looking in Wikipedia: http://en.wikipedia.org/wiki/String_searching_algorithm
I'd suggest going for either:
Rabin–Karp algorithm: http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_string_search_algorithm
Knuth–Morris–Pratt algorithm: http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
They are both really good and efficient algorithms, and both are fairly easy to implement.

Reading a text file, character by character in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am currently trying to work with a custom text file to read quests for a small game, however i am having trouble getting the code to read each character, I've done my research and somehow come up with nothing. I am unsure of how to read a .txt file character by character, so if anyone can help or point me in the right direction it would be strongly appreciated.
Path path = Paths.get("filename");
try (Scanner scanner = new Scanner(path, ENCODING.name())){
while (scanner.hasNextLine()){
String s = scanner.nextLine();
for(char c : s.toCharArray()) {
// your code
}
} catch(IOException e) {/* Reading files can sometimes result in IOException */}
If you want to read each character from file you could do something like this:
BufferedReader r=new BufferedReader(new FileReader("file.txt"));
int ch;
while((ch=r.read())!=-1){
// ch is each character in your file.
}
Good luck
File file = new File("text.txt");
Scanner in = new Scanner(file);
// option 1
while(in.hasNext())
{
String temp = in.next();
char[] temparr = temp.toCharArray();
for(Character j: temparr)
{
//do someting....
}
}
// or option 2
in.useDelimiter("");
while(in.hasNext())
{
temp = in.next();
//do something
}
Option 1 gives you the ability to manipulate the string char by char if the condition is true.
Option just reads one char at a time and lets you preform an action but not manipulate the string found in the text file.
public void method() throws FileNotFoundException
if you dont want to use a try catch

Categories