前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >每日一问第1期 | 截取字符串

每日一问第1期 | 截取字符串

作者头像
AlbertYang
发布2020-09-08 15:21:03
2800
发布2020-09-08 15:21:03
举报

第0期答案

上期问题每日一问第0期 | 大小写字符转换

问题分析:

本问题比较简单,思路是遍历字符串中的字符,然后判断字符串中的字符如果是大写字母就变成了小写,如果是小写字母就变为大写。在Java中我们可以使用toCharArray()方法把字符串变为字符数组,通过Character.toUpperCase()方法把小写字母变为大写,通过Character.toLowerCase()方法把大写字母变为小写。

代码:

代码语言:javascript
复制
package com.albertyy.AlbertYang;

import java.util.Scanner;

public class String_Substitution {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    System.out.println(substitutionStr(str));
  }

  public static String substitutionStr(String str) {
    char[] c = str.toCharArray();
    for (int i = 0; i < c.length; i++) {
      if ('a' <= c[i] && c[i] <= 'z') {
        c[i] = Character.toUpperCase(c[i]);
      } else if ('A' <= c[i] && c[i] <= 'Z') {
        c[i] = Character.toLowerCase(c[i]);
      }
    }
    String s = new String(c);
    return s;
  }

}

读者小白提供的答案:

代码语言:javascript
复制
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);        
        String str1 = sc.nextLine();
        System.out.println(changeStr(str1));        
    }
    public static String changeStr(String str){  
        char[] ch = str.toCharArray();          
        int a = 'A'-'a';   //获得大小写之间差值  
        for(int i = 0; i < ch.length; i++){  
            if('a' <= ch[i] && ch[i] <= 'z'){  
                ch[i] = (char)(ch[i]+a);  
            }else if('A' <= ch[i] && ch[i] <= 'Z'){  
                ch[i] = (char)(ch[i]-a);  
            }           
        }  
          String s=new String(ch);
        return s;  
    }  
}

每日一问|今日问题

写一个函数,函数中传入2 个参数,1 个String类型的字符串,1 个int类型的字节数量,返回值为截取的字符串,要求字符串中的中文不能出现乱码:如(“我ABC”,4)应该截为“我AB”,输入(“我ABC 汉DEF”,6)应该输出为“我ABC”而不是“我ABC+汉的半个”,请写出这个函数。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-10-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 AlbertYang 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档