string in java example

string in java example of use

	String str = "abc";
	char [] chArray ={'a','b','c'}; 
	String str2 = new String(chArray); // "abc"
 
	String str3 = "Get index of";
	// Returns the index within this string of 
	// the first occurrence of the specified character.
	int nIndexOfChar = str3.indexOf('G'); // 0
 
	// Returns the index within this string of 
	// the first occurrence of the specified substring.
	int nIndexOfString = str3.indexOf("index"); // 4
 
	// Returns the index within this string of the 
	// rightmost occurrence of the specified substring.
	int nLastIndexOfString = str3.lastIndexOf("of"); // 10
 
 
	int nLengthOfString = "index".length(); // 5
	int nStartIndex = 4;
	int nEndIndex = 4 + nLengthOfString;
 
	String sSubstr = str3.substring(nStartIndex, nEndIndex); // index
	System.out.print(sSubstr); // 4
 
//formatted output 
final String MY_STRING = "text1:%s;text2:%s";
String str = String.format(MY_STRING,"FIRST", "SECOND");	
System.out.print(str );
// text1:FIRST;text2:SECOND
 
// string to utf-8 conversion in java example
	String original = "řščš";
	    byte[] utf8Bytes = original.getBytes("UTF8");
	    byte[] defaultBytes = original.getBytes();
 
	    String roundTrip = new String(utf8Bytes, "UTF8");
	    System.out.println("roundTrip = " + roundTrip);	
 
     // split string to array java example
     String str = "one,two,three,four,five";
     String[] arrayOfElements = str.split(",");
     for (int i = 0; i < arrayOfElements .length; i++)
       System.out.println(arrayOfElements [i]);
     }
 
     // convert string to int java example
    String str4 = new String("184");
    int intConvertFromString = Integer.parseInt(str4);
 
    // string replace java example
    String text = "Hello word!";
    String newText = text.replace("word", "world");     // Hello world!
 
 
 
 char[]	toCharArray() 
          //Converts this string to a new character array.
 String	toLowerCase() 
          //Converts all of the characters in this String to lower case using 
          //the rules of the default locale.
 String	toLowerCase(Locale locale) 
          //Converts all of the characters in this String to lower case using 
          //the rules of the given Locale.
 String	toString() 
          //This object (which is already a string!) is itself returned.
 String	toUpperCase() 
          //Converts all of the characters in this String to upper case using 
          //the rules of the default locale.
This entry was posted in Android Examples Code and tagged , , . Bookmark the permalink.


Comments are closed.



8,280 views