String lower = Name.toLowerCase();
int a = Name.indexOf(" ",0);
String first = lower.substring(0, a);
String last = lower.substring(a+1);
char f = first.charAt(0);
char l = last.charAt(0);
f = Character.toUpperCase(f);
l = Character.toUpperCase(l);
String newname = last +" "+ first;
System.out.println(newname);
i want to take variables F and L and replace the lowercase first letters in last and first so they will be uppercase. How can I do this? i want to just replace the first letter in the last and first name with the char first and last
if you are trying to do what i think you are, you should consider using the apache commons-lang library, then look at:
WordUtils.capitalize
obviously, this is also open source, so for the best solution to your homework i'd take a look at the source code.
However, if i were writing it from scratch (and optimum performance wasn't the goal) here's how i would approach it:
public String capitalize(String input)
{
// 1. split on the negated 'word' matcher (regular expressions)
String[] words = input.toLowerCase().split("\\W");
StringBuffer end = new StringBuffer();
for (String word : words)
{
if (word.length == 0)
continue;
end.append(" ");
end.append(Character.toUpperCase(word.charAt(0)));
end.append(word.substring(1));
}
// delete the first space character
return end.deleteCharAt(0).toString();
}
While there's more efficient ways of doing this, you almost got it. You'd just need to concatenate the uppercase chars with the first and last name, bar the first character.
String newname = "" + l + last.subString(1) + " " + f + first.subString(1);
EDIT:
You could also use a string tokenizer to get the names as in:
StringTokenizer st = new StringTokenizer(Name);
String fullName = "";
String currentName;
while (st.hasMoreTokens()) {
/* add spaces between each name */
if(fullName != "") fullName += " ";
currentName = st.nextToken();
fullName += currentName.substring(0,0).toUpperCase() + currentName.substring(1);
}
String name = "firstname lastname";
//match with letter in beginning or a letter after a space
Matcher matcher = Pattern.compile("^\\w| \\w").matcher(name);
StringBuffer b=new StringBuffer();
while(matcher.find())
matcher.appendReplacement(b,matcher.group().toUpperCase());
matcher.appendTail(b);
name=b.toString();//Modified Name
Related
I have a String/Value "2.450,00. I want to get the Integer value from it. For that, I need to remove the " in front of the 2.
First you want to remove the comma sign and the decimals since an int (Integer) is a whole number.
str = str.split(",")[0];
This will split the string on the "," and take the first index which contains the string "2.450". Then you want to remove the punctuation. This can be done by replacing everything which is not a number with an empty space "".
str = str.replaceAll("[^0-9]", "");
Lastly, you want to convert the string to an integer.
int strAsInt = Integer.parseInt(str);
Full code:
public static void main(String[] args) {
// The initial value
String str = "2.450,00";
str = str.split(",")[0];
str = str.replaceAll("[^0-9]", "");
int strAsInt = Integer.parseInt(str);
// This will print the integer value 2450
System.out.println(strAsInt);
}
One liner:
int stringAsInt = Integer.parseInt(str.split(",")[0].replaceAll("[^0-9]", ""));
Try the below snippet. Use substring method to remove "
public static void main(String[] args) {
String str = "\"2.450,00";
// prints the substring after index 1 till str length
String substr = str.substring(1);
System.out.println("substring = " + substr);
}
At first, you need to remove any non-digit character (excluding the '.' and ',' characters) from the input string, the regex "[^\\d\\,\\.]" may help you with this:
final String inputString = "Total: 100.000,05$";
final String numberString = inputString.replaceAll("[^\\d\\,\\.]", "");
The next step is a formatting digit string into a valid double form. At this step, you'll need to replace '.' with an empty string and the ',' with a dot '.'.
final String formattedNumberString = numberString
.replace(".","")
.replace(',', '.');
And, in the end, you are finally able to parse a valid number:
double inputNumber = Double.parseDouble(formattedNumberString);
(1) Remove double quote from string
String str = "\"2.450,00";
str = str.replace("\"", "")
(2) then you should replace the comma as well
str = str.replace(",", "")
(3) Finally you should use the
Integer.parseInt() method to convert String to Integer
int i = Integer.parseInt(str);
In a program where currency is input in the form £2 or 10p, for example, is there a method to split this into two variables in the form
currencyType = £
currencyValue = 2
or
currencyType = p
currencyValue = 10
where currencyType is a string and currencyValue is an int?
An idea for a solution without regular expressions, although I'd prefer one of those:
String entry = "€2.73";
StringBuilder currency = new StringBuilder();
StringBuilder value = new StringBuilder();
for (char c : entry.toCharArray()) {
if (Character.isDigit(c) || c == '.' || c == ',') {
value.append(c);
} else {
currency.append(c);
}
}
System.out.println("Value = " + value + " Currency = " + currency);
Use patten and matcher classes like below. \d+ matches one or more digits where \D+ matches one or more non-digit characters.
String s1 = "£2";
Matcher m = Pattern.compile("(\\D+)|(\\d+)").matcher(s1);
while(m.find())
{
if (m.group(1) != null)
System.out.println("Currency Type: " + m.group(1));
if (m.group(2) != null)
System.out.println("Currency Value: " + m.group(2));
}
Output:
Currency Type: £
Currency Value: 2
OR
Use this regex, if you want to deal also with the decimal value.
Pattern.compile("(\\D+)|(\\d+(?:\\.\\d+)?)");
DEMO
You can use this regular expression to get your result: "(.*?)([\\d,]*)(.*?)"
This will split the input into three groups:
1) Leading currency token
2) Value token (can contain a ',', in the string version you can replaceAll ',' with '' and then convert to integer)
3) Trailing currency token
By looking at the groups from the regex, you can figure out if the leading or trailing currency is present and then get the value from the second group. You can write the code yourself by looking up usage for java regex.
You can input your value as a string, split it normally with the split function and assign each value to its own string. Then convert the string to an integer.
int currencyValue = Integer.parseInt(array[0]);
String currencyType = array[1];
array[] is the array that you split the string into.
String input = user_input.nextLine();
char[] array = input.toCharArray();
for(int i = 0; i < input.length(); i++) {
if (Character.isLetter(array[i])){
//use .split based on the output of the if statement
}
}
I have a string .. I need to search for some particular texts inside this string if it is present total numbers need to be returned.
I know how to return a character of particular place
String string = "Hi How are you";
b = string.contains("H") ;
But I need to get multiple characters for example..I need to search for 'A' and 'S' inside a string and I need number of times it is coming.
how I will write the code for that.I know how to search in a particular place and search for a particular character. But how for more than i character and return its total number.
String string = "Hai How are you!";
char aChar = anotherPalindrome.charAt(9);
I know it will reeturn 9th place character.
String string = "Niagara. O roar again!";
String roar = string.substring(5, 7);
I know it will return 'How'
You have to use regular expressions. Android provides the Pattern class to this kind of things.
You can do like this here three characters AJS can be searched.. if you need to search its small characters give like 'AaJaSs'..
String string;
Pattern pattern = Pattern.compile("([AJS])"); //case insensitive
Matcher matcher = pattern.matcher(String);
int count = 0;
while (matcher.find()) count++;
Try looping with help of the indexOf() method.
Example:
String exampleString = "Hai How are you!";
String searchedString = "H";
int index = exampleString.indexOf(searchedString , 0);
int counter = 0;
while(index != -1) {
counter++;
int index = exampleString.indexOf(searchedString , index);
}
System.out.println("The character " + searchedString + " occurs " + counter + " times.");
You can make a method to count the frequency of the character in the string :
public static int count(char character){
return str.toUpperCase().split((""+character).toUpperCase()).length - 1;
}
Then use this method as shown below:
b = string.count('H');
b = string.count('A');
Here is SS of the whole question. http://prntscr.com/1dkn2e
it should work with any sentence not just the one given in the example
I know it has to do something with strings. Our professor has gone over with these string methods
http://prntscr.com/1dknco
This is only a basic java class so don't use any complicated stuff
here is what I have, don't know what to do after this
any help would be appreciated.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
}
}
You can use public String[] split(String regex):
splitted = sentence.split("\\s+");
splitted[0] Is the first word.
splitted[splitted.length - 1] Is the last word.
Since your'e not allowed to use String#split, you can do this trick:
myString = myString.substring(0, myString.lastIndexOf(" ")) + firstWord;
By doing this, you'll have a substring which contains the sentence without the last word. (For extracting the first word, you can use String#indexOf.
firstWord is the first word you extracted before (I'll not solve the whole problem for you, try to do it by yourself, it should be easy now)
Well as it seem your looking for very simple string arithmetic.
So that's the simplest i could do:
// get the index of the start of the second word
int index = line.indexOf (' ');
// get the first char of the second word
char c = line.charAt(index+1);
/* this is a bit ugly, yet necessary in order to convert the
* first char to upper case */
String start = String.valueOf(c).toUpperCase();
// adding the rest of the sentence
start += line.substring (index+2);
// adding space to this string because we cut it
start += " ";
// getting the first word of the setence
String end = line.substring (0 , index);
// print the string
System.out.println(start + end);
try this
String str = "Java is the language";
String first = str.split(" ")[0];
str = str.replace(first, "").trim();
str = str + " " + first;
System.out.println(str);
Here is Another way you can do this.
UPDATED: Without Loops
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
int spacePosition = sentence.indexOf(" ");
String firstString = sentence.substring(0, spacePosition).trim();
String restOfSentence = sentence.substring(spacePosition, sentence.length()).trim();
String firstChar = restOfSentence.substring(0, 1);
firstChar = firstChar.toUpperCase();
restOfSentence = firstChar + restOfSentence.substring(1, restOfSentence.length());
System.out.println(restOfSentence + " " + firstString);
keyboard.close();
I have a string, for ex:
There exists a word *random*.
random will be a random word.
How can I use a regular expression to replace every character of random with * and have this result:
There exists a word ********.
So the * replaces every character, in this case 6 characters.
Notice that I am after to replace only the word random, not the surroundings *.
So far I have:
str.replaceAll("(\\*)[^.]*(\\*)", "\\*");
But it replaces *random* with *, instead of the desired ******** (total of 8).
Any help, really appreciated...
If you have just a single word like that: -
As far as current example is concerned, if you are having just a single word like that, then you can save yourself from regex, by using some String class methods: -
String str = "There exists a word *random*.";
int index1 = str.indexOf("*");
int index2 = str.indexOf("*", index1 + 1);
int length = index2 - index1 - 1; // Get length of `random`
StringBuilder builder = new StringBuilder();
// Append part till start of "random"
builder.append(str.substring(0, index1 + 1));
// Append * of length "random".length()
for (int i = 0; i < length; i++) {
builder.append("*");
}
// Append part after "random"
builder.append(str.substring(index2));
str = builder.toString();
If you can have multiple words like that: -
For that, here's a regex solution (This is where it starts getting a little complex): -
String str = "There exists a word *random*.";
str = str.replaceAll("(?<! ).(?!([^*]*[*][^*]*[*])*[^*]*$)", "*");
System.out.println(str);
The above pattern replaces all the characters that is not followed by string containing even numbers of * till the end, with a *.
Whichever is appropriate for you, you can use.
I'll add an explanation of the above regex: -
(?<! ) // Not preceded by a space - To avoid replacing first `*`
. // Match any character
(?! // Not Followed by (Following pattern matches any string containing even number of stars. Hence negative look-ahead
[^*]* // 0 or more Non-Star character
[*] // A single `star`
[^*]* // 0 or more Non-star character
[*] // A single `star`
)* // 0 or more repetition of the previous pattern.
[^*]*$ // 0 or more non-star character till the end.
Now the above pattern will match only those words, which are inside a pair of stars. Provided you don't have any unbalanced stars.
You can extract the word between * and do a replaceAll characters with * on it.
import java.util.regex.*;
String txt = "There exists a word *random*.";
// extract the word
Matcher m = Pattern.compile("[*](.*?)[*]").matcher(txt);
if (m.find()) {
// group(0): *random*
// group(1): random
System.out.println("->> " + m.group(0));
txt = txt.replace(m.group(0), m.group(1).replaceAll(".", "*"));
}
System.out.println("-> " + txt);
You can see it on ideone: http://ideone.com/VZ7uMT
try
String s = "There exists a word *random*.";
s = s.replaceAll("\\*.+\\*", s.replaceAll(".*(\\*.+\\*).*", "$1").replaceAll(".", "*"));
System.out.println(s);
output
There exists a word ********.
public static void main(String[] args) {
String str = "There exists a word *random*.";
Pattern p = Pattern.compile("(\\*)[^.]*(\\*)");
java.util.regex.Matcher m = p.matcher(str);
String s = "";
if (m.find())
s = m.group();
int index = str.indexOf(s);
String copy = str;
str = str.substring(0, index);
for (int i = index; i < index + s.length(); i++) {
str = str + "*";
}
str = str + copy.substring(index + s.length(), copy.length());
System.out.println(str);
}