简体   繁体   English

如何基于Java中的值从String获取垂直字符?

[英]How to get Perticular character from String based on value in Java?

Here i have String base="flames" and value will be dynamic.Based on values i need to get the character from base string.if value=0 i need to get output 'f' and if value more than 6 then i need to start 'f as 7' then print particular value.If value=10 then i need to get output as 'm'.Can anybody help me how to get this.This is my code. 在这里,我有String base =“ flames”,值将是动态的。基于值,我需要从基本string中获取字符。如果value = 0,则需要获取输出'f',如果值大于6,则需要开始'f as 7'然后打印特定的值。如果value = 10然后我需要将输出输出为'm'。有人可以帮助我如何获得它。这是我的代码。

public class demo {

public static void main(String[] args) {
    String base = "FLAMES";
    int value = 6;
    if (base.length() >= value) {
        System.out.println(value);
    }
 }
}

Your help will be appreciated. 您的帮助将不胜感激。

Try mod operator: 尝试mod运算符:

int value = 6;
System.out.println(base.charAt(value % base.length()));//F
value = 7;
System.out.println(base.charAt(value % base.length()));//L

Remember You are saying 0 should give you F, so 10 would give you E and not M as below 请记住,您说的是0应该给您F,所以10会给您E而不是M如下

FLAMESFLAMES
0 1 2 3 4 5 6 7 8 9 10 11

public static void main(String[] args) {
        String base = "FLAMES";
        int value = 1;
        value--;
        value = value % base.length();
        System.out.println(base.charAt(value));
     }

You can use modulus division in case the value is larger than the length of the string. 如果值大于字符串的长度,则可以使用模数除法。 This will give you the character for any input. 这将为您提供任何输入的字符。 Just add 1 to number I edited my post. 只需在我编辑帖子的号码上加1。

String - String is character array in java, and array always start with zero index. String -字符串是Java中的字符数组,并且数组始终以零索引开头。

F   L   A   M   E   S  
0   1   2   3   4   5

But, as per your question you need 但是,根据您的问题,您需要

    0 => F  
    7 => F  // String length is 6, but array index start from 0.
   10 => M

Modified Code : Here I have manged index if the value is greater then 7. 修改后的代码:如果值大于7,则在此处进行了索引管理。

public class demo {

public static void main(String[] args) {
    String base = "FLAMES";
    int value = 10;  // get input 
    char c=base.charAt(value%base.length());  

    if(value>=7){ // if value exceeds the 6, 
        value = value-1;  // you have to do value-1 to manage index.
        c=base.charAt(value%base.length());
    }

    System.out.println("char : "+c);  // print result
 }

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

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