繁体   English   中英

如何将String转换为java中的字符数组

[英]How can I convert String into array of characters in java

import java.util.*;

public class prac9 
{
    public static void main(String[] args){
    Scanner scn=new Scanner(System.in);

    int count=0;
    String x,str=" ";

    System.out.println("Regular Expression is (a+b)(ab+ba)*");
    System.out.println("Enter a Word: ");
    x=scn.nextLine();  //here simple x string type of varible

    if(x[0]=="a"|| x[0]=="b")  //here x array of string type of varible
    {                          //prac9.java:15: error: array 
                             // required,but String found


         for(int i=1; i<x.length(); i++)
         {
             str+=x[i];  
             if((i%2==0)==true)
             {
                 if(str=="ab" || str=="ba")
                 {
                     count=count+2;
                     str=" ";
                 }
             }

         }
         if((count+1)==(x.length())){
             System.out.println("Acceptable"); 
         }
         else{
             System.out.println("Not Acceptable");
         }

    }
    else{ 
        System.out.println("Not Acceptable..");
    }
}

请尽可能简单地帮助我。 正如我在上面的评论中提到的,它给了我一个错误。 我知道它在说什么,但我无法弄清楚如何将String转换为数组,以便我可以检查用户给出的每个字符。 实际上,这段代码是用C ++编写的。 我刚把它转换成Java语言。

if(x[0]=="a"|| x[0]=="b")

可以改为:

if(x.startsWith("a") || x.startsWith("b"))

str+=x[i];

可以改为:

str+=x.charAt(i);

最后:

 if(str=="ab" || str=="ba")

应改为

 if(str.equals("ab") || str.equals("ba"))

您可以使用charAt访问字符串的第一个字符,如下所示 -

x.charAt(0) == 'a'

因为那将返回字符串的第一个字符(基于起始索引= 0)

x是一个String,你需要将它转换为一个chars数组,然后将每个char与'a''b' 要做到这一点, if(x[0]=="a"|| x[0]=="b")替换这行代码

char[] x_chars = x.toCharArray();
if (x_chars[0] == 'a' || x_chars[0] == 'b') {
   ...
}

如果检查文档

https://docs.oracle.com/javase/6/docs/api/java/lang/String.html你可以找到方法

x.charAt(0)

在java中使用而不是x [0]。

您的“x”变量是String类型,而不是数组。 要将“x”声明为字符串数组,您应该使用

String x[] = new String[n];  //here 'n' is number of elements you store in your 'x' array

此外,如果您不知道有多少元素可以包含在数组中,那么根据您的要求也可以增长和缩小,您可以像这样使用“ArrayList”;

ArrayList<String> al=new ArrayList<String>();  
al.add("J"); //add 'J' as 1st element of 'al'
al.add("a");
al.add("v");
al.add("a");
System.out.println("element at 2nd position: "+al.get(2));  //get 'a'
al.remove(0)  //to remove 'J'
.............

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM