simple string concat manipulation in java - 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" );
}
}

Related

String return value in recursive function in java

So I'm practicing java currently, I'm a beginner and I try to explain all the examples that I code so I can understand how and why things are like that. I understand the concept of recursion but I came across this problem when I tried to explain this code:
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
String str;
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
str = scanner.nextLine();
scanner.close();
String reversed = reverseString(str);
System.out.println("The reversed string is: " + reversed);
}
public static String reverseString(String str)
{
if (str.isEmpty())
return str;
//Calling Function Recursively
return reverseString(str.substring(1)) + str.charAt(0);
}
}
With my knowledge so far about recursion, I tried to explain it like this.
Let's have for example a string "Petar":
reverseString(etar)+P
reverseString((tar)+etar)+P
reverseString((ar)+tar+etar)+P
reverseString((r)+ar+tar+etar)+P
-----------------------------------
r+ar+tar+etar+P
I noticed that the right answer is the first character from every individual piece, so I must be close.
Thank you for your time and I'm sorry if I didn't express myself clearly, I'm from Europe (sry bad inglish).
You doing good for first line reverseString(etar)+P you keep at the end only the *first char**, just do the same for next lines
put first char at the end
send the rest to the method
reverseString(etar)+P
reverseString(tar) +e+P
reverseString(ar) +t+e+P
reverseString(r) +a+t+e+P
reverseString('') +r+a+t+e+P // stops when empty string is passed
You got the first call right but the others were a bit off. In each recursive call you return the the string with the first character at the end instead of the begining. Thus, the recursion looks something like this:
reverseString("Petar")
return reverseString("etar") + "P"
return reverseString("tar") + "e"
return reverseString("ar") + "t"
return reverseString("r") + "a"
return reverseString("") + "r"
return ""
So the function will return: (((((("")+"r")+"a")+"t")+"e")+"P"), which is "rateP".
It should become clear when start with the simplest possible example: the empty string and string of size 1. Then substituting arguments of each call, to make it more obvious:
// string.isEmpty() is true, so the empty string is returned immediately
reverse("") -> ""
reverse("a") -> reverse("") + 'a' -> ("") + 'a' -> "a"
These are the trivial examples, let's try it with longer strings:
reverse("ab") -> reverse("b") + 'a'
reverse("abc") -> reverse("bc") + 'a'
-> (reverse("c") + 'b') + 'a'
-> ((reverse("") + 'c') + 'b') + 'a'
-> ((("") + 'c') + 'b') + 'a'
-> "cba"
The general pattern should be clear now. For the sake of completeness, let's manually "unroll" the recursive calls for a 4 character string:
reverse("abcd") -> reverse("bcd") + 'a'
-> (reverse("cd") + 'b') + 'a'
-> ((reverse("d") + 'c') + 'b') + 'a'
-> (((reverse("") + 'd') + 'c') + 'b') + 'a'
-> (((("") + 'd') + 'c') + 'b') + 'a'
-> "dcba"
It works like this:
reverseString("Peter") =
reverseString("eter") + P =
(reverseString("ter") + e) + P =
((reverseString("er") + t) + e) + P =
(((reverseString("r") + e) + t) + e) + P =
((((reverseString("") + r) + e) + t) + e) + P =
(((("" + r) + e) + t) + e) + P =
((((r) + e) + t) + e) + P =
(((r + e) + t) + e) + P =
(((re) + t) + e) + P =
((re + t) + e) + P =
((ret) + e) + P =
(ret + e) + P =
(rete) + P =
rete + P =
reteP
On your example when your function reaches only one character like
Peter when it becomes only "P"
and the string is not empty you call
substring(1)
Which calls an index out of the range while the string only have P on index 0 and none on index 1
You have to put a base case that checks if the string length is equal to 1 or less

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

How to only add something to a string if it doesn't contain it?

I am making a Lipogram program where any words with the banned letter are printed, however, the words are sometimes printed twice. How do I get it to not repeat the words?
Here is my code:
public String allWordsWith(char letter) {
String str = "";
String word = "";
s = s.replace(".", " ");
s = s.replace(",", " ");
s = s.replace("?", " ");
s = s.replace("!", " ");
s = " " + s + " ";
for (int i = 0; i <= s.lastIndexOf(letter); i++) {
if (s.charAt(i) == letter) {
if (str.contains(s.substring(s.lastIndexOf(" ", i), s.lastIndexOf(" ", i) + 1) + '\n') == true) {
} else {
word += s.substring(s.lastIndexOf(" ", i), s.indexOf(" ", i)) + '\n';
str += word;
}
}
}
return str;
}
Important clarification: Is the function run with the letter chosen as "o" on the string "hello hi hello howdy" meant to return "hello hello howdy" or "hello howdy". I.e., if the word appears twice, do you want to print it twice, or do you only want to print it once regardless of repetition?
If only once regardless of repetition, then you should be using a Set to store your data.
However, I think there's a chance you're instead dealing with an issue that when running the function with the letter chosen as "l" on that same string, "hello hi hello howdy", you are getting an output of "hello hello hello hello". Correct?
The issue here is that you are checking every letter and not testing each word. To fix this, I would use:
String[] words = s.split(" ");
to create an array of your words. Test each value in that array to see if it contains the given letter using:
if(words[index].contains(letter)){
str += " " + words[index];
}

converting a string; keyboard entry in 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().

Categories