Wednesday, March 27, 2013

Java;Notes - 12.) Fun with Strings

As you have seen in some of my programs the use of Strings is nothing new. It really helps to be able to use them to make things make more sense. As was a great example two posts ago about rounding numbers either up or down. Had I not added the strings explaining what each output was and had I not shown the code the numbers would have just been numbers. Big whoop anyone can print out numbers its as simple as:

  1. int x = 4;
  2. System.out.println(x);
Or if your really lazy:
  1. System.out.println("3.14159");
Not the last one was a string that was created in the moment. The kinds of strings we are going to be reviewing now are likely a mix of the above and the kinds of strings that hold their own variables and meanings.

To make a static string all you need to do is either of the following:
  • String e = ""; // this will create an empty string which can be useful if you want to input something.
  • String greeting = "Hello!";
Call out the function (String)<Variable> = {Meaning}
Creating strings is not a hard concept to grasp... however what comes next might take a little brain work.

A substring is basically using one already made string to make another one using the characters provided in the main string. Like so:
  • String greeting = "Hello!";
  • String s = greeting.substring(0, 3) 
This will output all of the characters used from point 0(h) through point 3(l) so when you:
  • System.out.println(s);
You will get an output of "Hel"

String Concatenation: 
String concatenation is another simple one. Think of it as "Adding Strings" so the syntax looks like:
  • variable = string1 + string2;
A proper looking code example would be:
  1. int age = 13;
  2. String rank = "PG";
  3. String rating = rank + age;
This should print out "PG13"

The Typical use of the above made string is one I have used before in my calculator:
  • System.out.println("The answer is: " + answer);
Strings are Immutable:
In basic principle java provides no ways to change a given character in a string. However to do this is rather simple. Take our greeting string from before if you wanted to change the "Hel" into "Help" you would simply concatenate a "p" onto the end of it so it would look something like:
  1. greeting = greeting.substring(0, 3) + "p";
In java you can not change a given string once it is made. However using the previous method you can reference a variable and generate a new string from it. It is for this reason that it is called Immutable. However as inefficient as this might seem the new string made has one great advantage. It is shared. Meaning the value of "greeting" goes two ways now.

Testing Strings for Equality:
You can test strings for equality just like you can test numbers. Use the equals method like so:
  • s.equals(t);
This will return true if the strings "s" and "t" are equal and false if they are not.
Note: "s" and "t" can be string variables or string constants. for example:
  • "Hello".equals(greeting);
To test if two strings are the same except for the upper / lowercase first letter you can do the following:
  • "Hello".equalsIgnoreCase("hello");
Empty and Null Strings:
The empty string "" is a string lenght of "0", You can test this by calling either of these two methods:
  • if (str.lenght() == 0)
  • if (str.equals(""))
An empty string holds a value of 0 however if if has no value associated with it it can hold a "null" value to test null you simply:

  • if (str == null)
Sometimes its good to see if a string is neither null or empty to do so you simply do the following:
  • if (str != null && str.lenght() != 0)
Note: you need to test if a string is null before doing the above or else you will get an error for your output.

Code Points and Code Units:

A code unit is defined simply as the number of letters in a unicode UTF-16 strings of numbers and letters to find out how many code points a string has you do the following:
  1. Make a string: String hello = "This is a string, how are you?";
  2. Make an int with the value assigned to it: int numLetters = hello.lenght();
  3. print it out: System.out.println(numLetters); //In this case it will print out 30
To get the true output of the length you must do this:
  • int cpCount = greeting.codePointCount(0, greeting.lenght());
To see what an individual character in a string is do the following:
  • s.charAt(n); // where as n = the position in the string you want to see.
In the case of s.length() you start at -1 So in practicality it would look like:
  1. char first = greeting.charAt(0); //Displays character #1: H
  2. char last = greeting.charAt(4); // Displays character #4: o
  3. System.out.println(first , last);
To get an indexed code point do the following:
  1. int index = greeting.offsetByCodePoints(0, i);
  2. int cp = greeting.codePointAt(index);
  3. System.out.println(index);
 So why is it important to know Code Points? Say you have a character that you dont know the meaning of if you want to know what it is you can use CodePoints to learn what it is.

Viewing Forward:
  1. String sentence = "This is a basic sentence sequence using letters and spaces in unicode!";
  2. int i = 0;
  3. int cp = sentence.codePointAt(i);
  4. System.out.println("\n" + sentence);
  5. if (Character.isSupplementaryCodePoint(cp)) i += 2;
  6. else i++;
  7. System.out.println(i);
Viewing reverse:

  1. String sentence = "This is a basic sentence sequence using letters and spaces in unicode!";
  2. int i = 0;
  3. int cp = sentence.codePointAt(i);
  4. System.out.println("\n" + sentence);
  5. i--;
  6. if (Character.isSurrogate(sentence.chatAt(i))) i-- ;
  7. else i--;
  8. System.out.println(i);
Here is an image of the output for all of this code:

All of the code in this section can be found: Here!

ADDENDUM: String Builder!
I failed to mention String Builder. String builder is a good tool to use if you need to get parts of a file to be placed in a program and it is really simple to use. Here is the basic outline:

  1. Stringbuilder builder = new Stringbuilder();
  2. builder.append(ch); //Appends a single character
  3. builder.append(str); // Appends a string
  4. String completedString = builder.toString(); // Finallizes and puts it in a nice neat string to print out later!

No comments:

Post a Comment