converting a string; keyboard entry in java - java

I have this code for converting a markdown string to html:
public static String convert(String str) {
if (str.equals("# "))
return " ";
if (str.matches("#+.+")) {
int n = str.length() - str.replaceFirst("#+", "").length();
return "<h" + n + ">" + str.substring(n) + "<h" + n + ">";
}
return str;
}
What I would like to know is how to get this class to get its string from keyboard entry?

You could use Scanner.nextLine():
String stringToConvert = new Scanner(System.in).nextLine();
System.out.println("Converted string is: " + convert(stringToConvert));

Just to keep it simple you can go by Console.readLine().

Related

Remove whitespace from start and end of String without trim()

How to remove whitespace from the start and end of a String without using the trim() method?
here is my code
public class StringTest {
public static void main(String[] args) {
String line = " Philippines| WNP|Naga |Camarines Sur|Naga Airport ";
//System.out.println(line);
int endIndex = line.indexOf("|");
String Country = line.substring(0, endIndex);
line = line.substring(endIndex + 1);
int endIndexCountry = line.indexOf("|");
String Code = line.substring(0, endIndexCountry);
line = line.substring(endIndexCountry + 1);
int endIndexCode = line.indexOf("|");
String City = line.substring(0, endIndexCode);
line = line.substring(endIndexCode + 1);
int endIndexCity = line.indexOf("|");
String State = line.substring(0, endIndexCity);
line = line.substring(endIndexCity + 1);
System.out.print("Code:" + Code + "____");
System.out.print("Country:" + Country + "____");
System.out.print("State:" + State + "____");
System.out.print("City:" + City + "____");
System.out.println("Airport:" + line+ "____");
}
}
and my output looks like this
Code: WNP____Country: Philippines____State:Camarines Sur____City:Naga ____Airport:Naga Airport ____
I need to look like this(without whitespaces)
Code:WNP____Country:Philippines____State:Camarines Sur____City:Naga____Airport:Naga Airport____
How to remove whitespace from the start and end of a String without
using the trim() method?
You can do it using a combination of regex patterns and String::replaceAll.
public class Main {
public static void main(String[] args) {
String str = " Hello ";
System.out.println("Before: " + str + "World!");
str = str.replaceAll("^[ \\t]+", "").replaceAll("[ \\t]+$", "");
System.out.println("After: " + str + "World!");
}
}
Output:
Before: Hello World!
After: HelloWorld!

How to extract the below pattern from a string?

I have a string which looks like below.
{(firstName1,lastName1,College1,{(24,25)},{(Street,23)},City1,Country1)}
I need to extract the details/values from the above and add them to a list. By details I mean:
["firstName1","lastName1","College1","24","25","Street","23","City1", "country1"]
How can I achieve the above? I tried the below method but not sure how to get all curly braces and brackets into the pattern.
private static String flattenPigBag(String pigdata) {
String s = "";
Pattern p = Pattern.compile("\\{(.*)}");
Matcher m = p.matcher(pigdata);
while (m.find()) {
s = m.group(1);
System.out.println("answer : " + s);
}
return s;
}
Try this:
String[] parts = str.replaceAll("}|\\{", "").split(",");
Are you forced to use a pattern? If not, feel free to use this.
private static List<String> flattenPigBag(String s) {
return Arrays.asList(s.replaceAll("[(){}]", "").split(","));
}
Output:
[firstName1, lastName1, College1, 24, 25, Street, 23, City1, Country1]
I assume you need to extract the individual fields for further processing. So here is what I would do. In my test program I just print out the fields, but I imagine in your program you may take those field values and use them somehow (e.g. apply them to some setters of a Java object)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatchingWithNamedCaptureGroup {
public static void main(String[] args) {
String regex = "\\{(\\("
+ "(?<firstName>[^,]*)"
+ ",(?<lastName>[^,]*)"
+ ",(?<college>[^,]*)"
+ ",\\{\\("
+ "(?<num1>\\d*)"
+ ",(?<num2>\\d*)\\)\\}"
+ ",\\{\\((?<street>[^,]*)"
+ ",(?<streetNum>\\d*)\\)\\}"
+ ",(?<city>[^,]*)"
+ ",(?<country>[^,]*)"
+ "\\))\\}";
String input
= "{(firstName1,lastName1,College1,{(24,25)},{(Street,23)},City1,Country1)}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if (m.find()) {
String firstName = m.group("firstName");
String lastName = m.group("lastName");
String college = m.group("college");
String num1 = m.group("num1");
String num2 = m.group("num2");
String street = m.group("street");
String streetNum = m.group("streetNum");
String city = m.group("city");
String country = m.group("country");
System.out.println(firstName
+ "," + lastName
+ "," + college
+ "," + num1
+ "," + num2
+ "," + street
+ "," + streetNum
+ "," + city
+ "," + country
);
} else {
System.err.println("Does not match!");
}
}
}
The output of this program is this:
firstName1,lastName1,College1,24,25,Street,23,City1,Country1

What's Wrong? Number Of Words In a Sentence Java

int numOfWords = str.length() - str.replace(" ", "").length();
Why does that not work? If str is equal to "Hello bye", numOfWords should equal 2, but when ran numOfWords equals 0. Any help would be greatly appreciated!
You are only replacing one blank, so the output will be 1 (at least this is what is produce in my JVM)
If you want to know the number of words then either add 1 to this number or use
str.split(" ").length;
Why dont you use :
int numOfWords = str.split(" ").length;
I hope out put is much clear
public static void main(String[] args) {
String str = "Hello bye";
System.out.println("Length of Input String = " + str.length() + " for String = " + str);
System.out.println("Length of Input String with space removed = " + str.replace(" ", "").length() + " for String = "
+ str.replace(" ", ""));
int numOfWords = str.length() - str.replace(" ", "").length();
System.out.println(numOfWords);
}
Output
Length of Input String = 9 for String = Hello bye
Length of Input String with space removed = 8 for String = Hellobye
1

Markdown algorithm: string difficulties

I started writing this algorithm:
public static String convert(String str) {
if (str.equals("# "))
return " ";
if (str.matches("#+.+")) {
int n = str.length() - str.replaceFirst("#+", "").length();
return "<h" + n + ">" + str.substring(n) + "<h" + n + ">";
}
return str;
}
}
So when I type, ####title, it returns < h4>title< /h4>
My problem is that when I write ####title###title, I would like it to return < h4>title< /h4> < h3>title< /h3> but it only returns < h4>title< /h4>...What am I doing wrong???
Thats because you are using the pattern: - #+.+.
Now, since . matches everything in Regex, so in the above pattern, it matches everything after an initial set of #'s.
So, for your input: - ####title###title, your pattern will match: -
#+ will match ####
.+ will match title###title
You need to change your regex to : - (#+[^#]+), and probably need to use Pattern class here to get the desired output, becaues you want to match every part of your string to the given pattern.
#+[^#]+ -> Will match the first set of # and then everything after that, except #. So it stops where the next set of #'s start.
Here's how you can use it: -
String str = "####title###title"; // str is the method parameter
if (str.equals("# "))
System.out.println(" ");
Pattern pattern = Pattern.compile("(#+[^#]+)");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
String str1 = matcher.group(1);
int n = str1.length() - str1.replaceFirst("#+", "").length();
System.out.println("<h" + n + ">" + str1.substring(n) + "</h" + n + ">");
}
OUTPUT: -
<h4>title</h4>
<h3>title</h3>
You are matching wrong string, try this one:
#+[^#]+
And of course you want to make call it recursivly or in a loop
You are replacing only the first occurrence of #+. Try replacing the if with a while and instead of return inside the if, append the result into a StringBuilder.
Something like:
String str = "####title###title2";
StringBuilder sb = new StringBuilder();
while (str.matches("#+.+")) {
int n = str.length() - str.replaceFirst("#+", "").length();
str = str.replaceFirst("#+", "");
int y = str.length();
if(str.matches(".+#+.+")) {
y = str.indexOf("#");
sb.append( "<h" + n + ">" + str.substring(0,y) + "<h" + n + ">");
str = str.substring(y, str.length());
} else {
sb.append( "<h" + n + ">" + str.substring(0,y) + "<h" + n + ">");
}
}
System.out.println(sb.toString());
}

simple string concat manipulation in java

I want to get the following output:
Hello Steve Andrews!
These are my variables:
a = "steve";
b = "Andrew"
I tried this:
System.out.print("Hello " + a + " " + b + "s");
I don't know where to put .toUpper() for steve. The s should be in uppercase. How do I do this?
Use StringUtils.capitalize(a),
"Hello " + StringUtils.capitalize(a) + " " + b + "s"
Capitalizes a String changing the first letter to title case as per Character.toTitleCase(char). No other letters are changed.
You could use StringUtils.capitalize(str), or if you want to do it by yourself:
public static String capitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuffer(strLen)
.append(Character.toTitleCase(str.charAt(0)))
.append(str.substring(1))
.toString();
}
You could also try using this method:
public static String capitalize(String str) {
str = (char) (str.charAt(0) - 32) + str.substring(1);
return str;
}
Though it should be noted that this method assumes that the first character in str is indeed a lowercase letter.
Finally, I tried to do it without stringutils.. But anyways, thanks to all who helped :)
public class Hello
{
public static void main(String[] args){
String a = "steve";
String b = "Andrew";
String firstletter = a.substring(0,1);
String remainder = a.substring(1);
String capitalized = firstletter.toUpperCase() + remainder.toLowerCase();
System.out.print("Hello " + capitalized + " " + b + "s" );
}
}

Categories