Showing posts with label CharAt. Show all posts
Showing posts with label CharAt. Show all posts

Problem 2: CharAt and length

Similar the previous problem, create a program that will allow the user to enter a string (word or phrase) that will also show the second character and the length based on the string entered by the user.

import java.io.*;
class s30
{
public static void main (String args[]) throws IOException
{
DataInputStream k=new DataInputStream (System.in);

String a;

System.out.println("Enter String: ");
a=k.readLine();
char s = a.charAt(1);
System.out.println(s);
System.out.println(a.length());
}
}

Problem: CharAt and String

Create a program that will display the first letter of a string as well as display the string's length. Note that the string will not be provided by the user.

class s30
{
public static void main (String args[])
{
String a = "Hello World";
char s = a.charAt(0);
System.out.println(s);
System.out.println(a.length());
}
}

CharAt and Length

CharAt

  • returns the character at the specified index in a string
  • written as CharAt() with the index inside the ()
  • the index starts with a zero (example: with the word Hi, H is 0 and i is 1)
  • includes special characters and spaces
example:
HelloWorld.CharAt(0) is the letter H
HelloWorld.CharAt(1) is the letter e
HelloWorld.CharAt(2) is the letter l
HelloWorld.CharAt(3) is the letter l
HelloWorld.CharAt(4) is the letter o
HelloWorld.CharAt(5) is the letter W


Length
  • shows the length of a string
  • starts at zero
  • includes special characters and spaces
  • written as string.length

Extended Search

Custom Search
Hello World