Skip to content

Instantly share code, notes, and snippets.

@adaptives
Created July 26, 2011 10:05
Show Gist options
  • Save adaptives/1106420 to your computer and use it in GitHub Desktop.
Save adaptives/1106420 to your computer and use it in GitHub Desktop.
Java Strings
package com.diycomputerscience;
/**
* This example explains Java Strings and a few commonly used methods
* in the {@link String} class
*
*/
public class JavaStrings {
public static void main(String[] args) {
String s1 = "prog:Java:Hello";
String s2 = new String(" World");
System.out.println(s1.substring(0,4));
if(s1.contains(":")) {
System.out.println("The string contains a ':' character");
}
if(s1.indexOf(':') != -1) {
System.out.println("The string contains a ':' character");
}
//Print the substring till the first occurrence of ":"
System.out.println(s1.substring(0,s1.indexOf(':')));
//Simple concatenation using the + operator
System.out.println(s1 + s2);
String tokens[] = s1.split(":");
System.out.println("Printing all the tokens in String '" + s1 + "'");
for(int i=0; i<tokens.length; i++) {
System.out.println(tokens[i]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment