How to find the first character of one dimensional string in java


How to find the first character of one dimensional string in java


public class solution{
public static void main(String args){
String priya={"priya","nandhni","nithesh","varan","rekha","sri"};
for(int i=0;i<priya.length;i++)
{
System.out.println(priya.charAt(i));
}
}
}



This is not working.How can I separate first letters p, n, n, v, r, s to a char array from the above string using java?





Have you tried some Java code yet?
– Tim Biegeleisen
Jul 1 at 15:02





Use String.charAt(index) to access the character in String
– Mạnh Quyết Nguyễn
Jul 1 at 15:03


String.charAt(index)





Post your code. Also specify what output you expect ? A String ("pnnvrs") ? An array ?
– c0der
Jul 1 at 15:07





@TimBiegeleisen am new to java
– priya priya
Jul 1 at 15:21




2 Answers
2



If you want to directly print the first character of every String without using the character array, then you can use this snippet:


public class solution{
public static void main(String args){
String priya={"priya","nandhni","nithesh","varan","rekha","sri"};
for(int i=0;i<priya.length;i++)
{
System.out.println(priya[i].charAt(0));
}
}



The only thing you are doing wrong is you are not specifying priya is an array, after specifying an array & its index value you can only use the string methods on it. So just replace your priya.charAt(i) with priya[i].charAt(0).



Hope this solve your problem.



You can try following snippet:


public static void main(String args){
String priya={"priya","nandhni","nithesh","varan","rekha","sri"};
char firstChars=new char[priya.length];
for(int i=0;i<priya.length;i++)
{
firstChars[i] = priya[i].charAt(0);
}
}



Then you can print or do some manipulating that you want





not working...shows error at priya.charAt(0)
– priya priya
Jul 1 at 15:48





I missing one thing, i updated, so try it
– Minh Trần
Jul 1 at 15:50





tq...but what does this line char firstChars=new char[priya.length]; mean?
– priya priya
Jul 1 at 15:58





That is a temporary array contains your output (array of first characters ).
– Minh Trần
Jul 1 at 16:00






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to make file upload 'Required' in Contact Form 7?

Rothschild family

amazon EC2 - How to make wp-config.php to writable?