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);
System.out.println(l);
how would i get the F and L variables converted to uppercase.
You can use Character#toUpperCase() for this.
char fUpper = Character.toUpperCase(f);
char lUpper = Character.toUpperCase(l);
It has however some limitations since the world is aware of many more characters than can ever fit in 16bit char range. See also the following excerpt of the javadoc:
Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the toUpperCase(int) method.
Instead of using existing utilities, you may try below conversion using boolean operation:
To upper case:
char upperChar = 'l' & 0x5f
To lower case:
char lowerChar = 'L' ^ 0x20
How it works:
Binary, hex and decimal table:
------------------------------------------
| Binary | Hexadecimal | Decimal |
-----------------------------------------
| 1011111 | 0x5f | 95 |
------------------------------------------
| 100000 | 0x20 | 32 |
------------------------------------------
Let's take an example of small l to L conversion:
The binary AND operation: (l & 0x5f)
l character has ASCII 108 and 01101100 is binary represenation.
1101100
& 1011111
-----------
1001100 = 76 in decimal which is **ASCII** code of L
Similarly the L to l conversion:
The binary XOR operation: (L ^ 0x20)
1001100
^ 0100000
-----------
1101100 = 108 in decimal which is **ASCII** code of l
Have a look at the java.lang.Character class, it provides a lot of useful methods to convert or test chars.
f = Character.toUpperCase(f);
l = Character.toUpperCase(l);
Since you know the chars are lower case, you can subtract the according ASCII value to make them uppercase:
char a = 'a';
a -= 32;
System.out.println("a is " + a); //a is A
Here is an ASCII table for reference
System.out.println(first.substring(0,1).toUpperCase());
System.out.println(last.substring(0,1).toUpperCase());
If you are including the apache commons lang jar in your project than the easiest solution would be to do:
WordUtils.capitalize(Name)
takes care of all the dirty work for you.
See the javadoc here
Alternatively, you also have a capitalizeFully(String) method which also lower cases the rest of the characters.
You can apply the .toUpperCase() directly on String variables or as an attribute to text fields. Ex: -
String str;
TextView txt;
str.toUpperCase();// will change it to all upper case OR
txt.append(str.toUpperCase());
txt.setText(str.toUpperCase());
Lets assume you have a variable you want split
String name = "Your name variable";
char nameChar = Character.toUpperCase(name.charAt(0));
I think you are trying to capitalize first and last character of each word in a sentence with space as delimiter.
Can be done through StringBuffer:
public static String toFirstLastCharUpperAll(String string){
StringBuffer sb=new StringBuffer(string);
for(int i=0;i<sb.length();i++)
if(i==0 || sb.charAt(i-1)==' ' //for first character of string/each word
|| i==sb.length()-1 || sb.charAt(i+1)==' ') //for last character of string/each word
sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
return sb.toString();
}
The easiest solution for your case - change the first line, let it do just the opposite thing:
String lower = Name.toUpperCase ();
Of course, it's worth to change its name too.
Related
I'm looking for a straightforward answer and can't seem to find one.
I'm just trying to see if the following is valid. I want to take the integer 7 and turn it into the character '7'. Is this allowed:
int digit = 7;
char code = (char) digit;
Thank you in advance for your help!
This conversion is allowed, but the result won't be what you expect, because char 7 is the bell character whereas '7' is 55 (0x37). Because the numeric characters are in order, starting with '0' at 48 (0x30), just add '0', then cast the result as a char.
char code = (char) (digit + '0');
You may also take a look at the Unicode characters, of which the printable ASCII characters are the same codes.
'7' is Unicode code point U+0037.
Since it is a code point in the Basic Multiligual Plane, and since char is a UTF-16 code unit and that there is a one-to-one mapping between Unicode code points in this plane and UTF-16 code units, you can rely on this:
(char) ('0' + digit)
Do NOT think of '7' as ASCII 55 because that prevents a good understanding of char... For more details, see here.
Nope. The char '7' can be retrieved from int 7 in these ways:
int digit = 7;
char code = Integer.toString(digit).charAt(0);
code = Character.forDigit(digit, 10);
If digit is between 0 and 9:
int digit = 7;
char code = (char)(((int)'0')+digit);
I looked for this about an hour now, but couldn't get any advise specific to my problem. What I'd like to do is take a string of 0's and 1's and manipulate a char that it fits the given String pattern. For example:
char c = 'b'
String s = "00000000 01100001";
Now I'd like to manipulate the bits in c, so that they match the bit pattern specified in s. As result c would be printed as 'a' (if I'm not completely wrong about it). Any help appreciated!
You can do
char a = (char) Integer.parseInt("0000000001100001", 2);
To do the conversion from binary string to Integer, use parseInt with the 2nd argument as 2.
int temp = Integer.parseInt("01100001", 2);
You can modify with binary operators (&,|,^), but if what you really want is to just assign a variable, you can do it with casts.
char c = 'c';
System.out.println((char)(c&temp));
System.out.println((char)temp);
How about:
String s = "00000000 01100001";
String[] w = s.split(" ");
char c = (char)(Integer.parseInt(w[0], 2) * 256 + Integer.parseInt(w[1], 2));
This allows for the leading zeroes of each byte to be omitted. If you know they're there, you can just replace the space out of the string and use a single parseInt() call:
char c = (char)Integer.parseInt(s.replace(" ", ""), 2);
So I just started reading "Java In A Nutshell", and on Chapter One it states that:
"To include a character literal in a Java program, simply place it between single quotes"
i.e.
char c = 'A';
What exactly does this do^? I thought char only took in values 0 - 65,535. I don't understand how you can assign 'A' to it?
You can also assign 'B' to an int?
int a = 'B'
The output for 'a' is 66. Where/why would you use the above^ operation?
I apologise if this is a stupid question.
My whole life has been a lie.
char is actually an integer type. It stores the 16-bit Unicode integer value of the character in question.
You can look at something like http://asciitable.com to see the different values for different characters.
In Java char literals represent UTF-16 (character encoding schema) code units. What you got from UTF-16 is mapping between integer values (and the way they are saved in memory) with corresponding character (graphical representation of unit code).
You can enclose characters in single quotes - this way you don't need to remember UTF-16 values for characters you use. You can still get the integer value from character type and put if for example in int type (but generally not in short, they both use 16 bits but short values are from -32768 to 32767 and char values are from 0 to 65535 or so).
If you look at an ASCII chart, the character "A" has a value of 41 hex or 65 decimal. Using the ' character to bracket a single character makes it a character literal. Using the double-quote (") would make it a String literal.
Assigning char someChar = 'A'; is exactly the same as saying char someChar = 65;.
As to why, consider if you simply want to see if a String contains a decimal number (and you don't have a convenient function to do this). You could use something like:
bool isDecimal = true;
for (int i = 0; i < decString.length(); i++) {
char theChar = decString.charAt(i);
if (theChar < '0' || theChar > '9') {
isDecimal = false;
break;
}
}
I am having some trouble with modifying Strings to be space delimited under the special case of adding spaces to all non-numerical characters.
My code must take a string representing a math equation, and split it up into it's individual parts. It does so using space delimits between values This part works great if the string is already delimited.
The problem is that I do not always get a space delimited input. To deal with this, I want to first insert these spaces so that the array is created properly.
What my code must do is take any character that is NOT a number, and add a space before and after it.
Something like this:
3*24+321 becomes 3 * 24 + 321
or
((3.0)*(2.5)) becomes ( ( 3.0 ) * ( 2.5 ) )
Obviously I need to avoid inserting space in the numbers, or 2.5 becomes 2 . 5, and then gets entered into the array as 3 elements. which it is not.
So far, I have tried using
String InputLineDelmit = InputLine.replaceAll("\B", " ");
which successfully changes a string of all letters "abcd" to "a b c d"
But it makes mistakes when it runs into numbers. Using this method, I have gotten that:
(((1)*(2))) becomes ( ( (1) * (2) ) ) ---- * The numbers must be separate from parens
12.7+3.1 becomes 1 2.7+3.1 ----- * 12.7 is split
51/3 becomes 5 1/3 ----- * same issue
and 5*4-2 does not change at all.
So, I know that \D can be used as a regular expression for all non-numbers in java. However, my attempts to implement this (by replacing, or combining it with \B above) have led either to compiler errors or it REPLACING the char with a space, not adding one.
EDIT:
==== Answered! ====
It wont let me add my own answer because I'm new, but an edit to neo108's code below (which, itself, does not work) did the job. What i did was change it to check isDigit, not isLetter, and then do nothing in that case (or in the special case of a decimal, for doubles). Else, the character is changed to have spaces on either side.
public static void main(String[] args){
String formula = "12+((13.0)*(2.5)-17*2)+(100/3)-7";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < formula.length(); i++){
char c = formula.charAt(i);
char cdot = '.';
if(Character.isDigit(c) || c == cdot) {
builder.append(c);
}
else {
builder.append(" "+c+" ");
}
}
System.out.println("OUTPUT:" + builder);
}
OUTPUT: 12 + ( ( 13.0 ) * ( 2.5 ) - 17 * 2 ) + ( 100 / 3 ) - 7
However, any ideas on how to do this more succinctly, and also a decent explanation of StringBuilders, would be appreciated. Namely what is with this limit of 16 chars that I read about on javadocs, as the example above shows that you CAN have more output.
Something like this should work...
String formula = "Ab((3.0)*(2.5))";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < formula.length(); i++){
char c = formula.charAt(i);
if(Character.isLetter(c)) {
builder.append(" "+c+" ");
} else {
builder.append(c);
}
}
Define the operations in your math equation + - * / () etc
Convert your equation string to char[]
Traverse through the char[] one char at a time and append the read char to a StringBuilder object.
If you encounter any character matching with the operations defined, then add a space before and after that character and then append this t o the StringBuilder object.
Well this is one of the algorithm you can implement. There might be other ways of doing it as well.
Is there a recommended way to escape <, >, " and & characters when outputting HTML in plain Java code? (Other than manually doing the following, that is).
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = source.replace("<", "<").replace("&", "&"); // ...
StringEscapeUtils from Apache Commons Lang:
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
// ...
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = escapeHtml(source);
For version 3:
import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
// ...
String escaped = escapeHtml4(source);
An alternative to Apache Commons: Use Spring's HtmlUtils.htmlEscape(String input) method.
Nice short method:
public static String escapeHTML(String s) {
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '\'' || c == '<' || c == '>' || c == '&') {
out.append("&#");
out.append((int) c);
out.append(';');
} else {
out.append(c);
}
}
return out.toString();
}
Based on https://stackoverflow.com/a/8838023/1199155 (the amp is missing there). The four characters checked in the if clause are the only ones below 128, according to http://www.w3.org/TR/html4/sgml/entities.html
There is a newer version of the Apache Commons Lang library and it uses a different package name (org.apache.commons.lang3). The StringEscapeUtils now has different static methods for escaping different types of documents (http://commons.apache.org/proper/commons-lang/javadocs/api-3.0/index.html). So to escape HTML version 4.0 string:
import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
String output = escapeHtml4("The less than sign (<) and ampersand (&) must be escaped before using them in HTML");
For those who use Google Guava:
import com.google.common.html.HtmlEscapers;
[...]
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = HtmlEscapers.htmlEscaper().escape(source);
Be careful with this. There are a number of different 'contexts' within an HTML document: Inside an element, quoted attribute value, unquoted attribute value, URL attribute, javascript, CSS, etc... You'll need to use a different encoding method for each of these to prevent Cross-Site Scripting (XSS). Check the OWASP XSS Prevention Cheat Sheet for details on each of these contexts. You can find escaping methods for each of these contexts in the OWASP ESAPI library -- https://github.com/ESAPI/esapi-java-legacy.
On android (API 16 or greater) you can:
Html.escapeHtml(textToScape);
or for lower API:
TextUtils.htmlEncode(textToScape);
For some purposes, HtmlUtils:
import org.springframework.web.util.HtmlUtils;
[...]
HtmlUtils.htmlEscapeDecimal("&"); //gives &
HtmlUtils.htmlEscape("&"); //gives &
org.apache.commons.lang3.StringEscapeUtils is now deprecated. You must now use org.apache.commons.text.StringEscapeUtils by
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons.text.version}</version>
</dependency>
While #dfa answer of org.apache.commons.lang.StringEscapeUtils.escapeHtml is nice and I have used it in the past it should not be used for escaping HTML (or XML) attributes otherwise the whitespace will be normalized (meaning all adjacent whitespace characters become a single space).
I know this because I have had bugs filed against my library (JATL) for attributes where whitespace was not preserved. Thus I have a drop in (copy n' paste) class (of which I stole some from JDOM) that differentiates the escaping of attributes and element content.
While this may not have mattered as much in the past (proper attribute escaping) it is increasingly become of greater interest given the use use of HTML5's data- attribute usage.
Java 8+ Solution:
public static String escapeHTML(String str) {
return str.chars().mapToObj(c -> c > 127 || "\"'<>&".indexOf(c) != -1 ?
"&#" + c + ";" : String.valueOf((char) c)).collect(Collectors.joining());
}
String#chars returns an IntStream of the char values from the String. We can then use mapToObj to escape the characters with a character code greater than 127 (non-ASCII characters) as well as the double quote ("), single quote ('), left angle bracket (<), right angle bracket (>), and ampersand (&). Collectors.joining concatenates the Strings back together.
To better handle Unicode characters, String#codePoints can be used instead.
public static String escapeHTML(String str) {
return str.codePoints().mapToObj(c -> c > 127 || "\"'<>&".indexOf(c) != -1 ?
"&#" + c + ";" : new String(Character.toChars(c)))
.collect(Collectors.joining());
}
The most of libraries offer escaping everything they can including hundreds of symbols and thousands of non-ASCII characters which is not what you want in UTF-8 world.
Also, as Jeff Williams noted, there's no single “escape HTML” option, there are several contexts.
Assuming you never use unquoted attributes, and keeping in mind that different contexts exist, it've written my own version:
private static final long TEXT_ESCAPE =
1L << '&' | 1L << '<';
private static final long DOUBLE_QUOTED_ATTR_ESCAPE =
TEXT_ESCAPE | 1L << '"';
private static final long SINGLE_QUOTED_ATTR_ESCAPE =
TEXT_ESCAPE | 1L << '\'';
private static final long ESCAPES =
DOUBLE_QUOTED_ATTR_ESCAPE | SINGLE_QUOTED_ATTR_ESCAPE;
// 'quot' and 'apos' are 1 char longer than '#34' and '#39'
// which I've decided to use
private static final String REPLACEMENTS = ""&'<";
private static final int REPL_SLICES = /* [0, 5, 10, 15, 19) */
5<<5 | 10<<10 | 15<<15 | 19<<20;
// These 5-bit numbers packed into a single int
// are indices within REPLACEMENTS which is a 'flat' String[]
private static void appendEscaped(
Appendable builder, CharSequence content, long escapes) {
try {
int startIdx = 0, len = content.length();
for (int i = 0; i < len; i++) {
char c = content.charAt(i);
long one;
if (((c & 63) == c) && ((one = 1L << c) & escapes) != 0) {
// -^^^^^^^^^^^^^^^ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// | | take only dangerous characters
// | java shifts longs by 6 least significant bits,
// | e. g. << 0b110111111 is same as >> 0b111111.
// | Filter out bigger characters
int index = Long.bitCount(ESCAPES & (one - 1));
builder.append(content, startIdx, i /* exclusive */).append(
REPLACEMENTS,
REPL_SLICES >>> (5 * index) & 31,
REPL_SLICES >>> (5 * (index + 1)) & 31
);
startIdx = i + 1;
}
}
builder.append(content, startIdx, len);
} catch (IOException e) {
// typically, our Appendable is StringBuilder which does not throw;
// also, there's no way to declare 'if A#append() throws E,
// then appendEscaped() throws E, too'
throw new UncheckedIOException(e);
}
}
Consider copy-pasting from Gist without line length limit.
UPD: As another answer suggests, > escaping is not necessary; also, " within attr='…' is allowed, too. I've updated the code accordingly.
You may check it out yourself:
<!DOCTYPE html>
<html lang="en">
<head><title>Test</title></head>
<body>
<p title="<"I'm double-quoted!">"><"Hello!"></p>
<p title='<"I'm single-quoted!">'><"Goodbye!"></p>
</body>
</html>