Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java编程:将每个单词的首字母和末字母替换为_&引用;_Java - Fatal编程技术网

Java编程:将每个单词的首字母和末字母替换为_&引用;

Java编程:将每个单词的首字母和末字母替换为_&引用;,java,Java,此方法的目的是将每个单词的第一个和最后一个字母替换为“\”。说到编码,我是一个完全的新手,所以我确信我的代码是相当不正确的。我认为我的代码开始运行不正常的地方是while循环 编辑:如何在不使用数组或其他方法(如split方法)的情况下创建此方法 public static String blankWords(String s1) { StringBuilder sb = new StringBuilder(); if(s1.length() > 2) { s

此方法的目的是将每个单词的第一个和最后一个字母替换为“\”。说到编码,我是一个完全的新手,所以我确信我的代码是相当不正确的。我认为我的代码开始运行不正常的地方是while循环

编辑:如何在不使用数组或其他方法(如split方法)的情况下创建此方法

public static String blankWords(String s1) {

    StringBuilder sb = new StringBuilder();
    if(s1.length() > 2) {
      sb.append(s1.charAt(0));
      for(int x = 1; x < s1.length() - 1; x = x + 1) {
        char y = ' ';
        while(y != s1.charAt(x)) {
          sb.append("_");
          x = x + 1;
        }
      }
      sb.append(s1.charAt(s1.length() - 1));
      return sb.toString();
    }
    return s1;
  }
公共静态字符串空白字(字符串s1){
StringBuilder sb=新的StringBuilder();
如果(s1.length()>2){
sb.追加(s1.字符(0));
对于(int x=1;x
我的代码输出的内容:

HW2.空白词(“这是一个测试”) java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:15 位于java.lang.String.charAt(未知源) at HW2.blankWords(HW2.java:73)

我的代码应该输出什么:

HW2.空白词(“这是一个测试”) “T_u_______________________________


没有必要

向前看1个字符,看看它是一个空格,还是当前字符是一个空格,在这种情况下,您可以附加它。否则,请确保添加下一个字符(skipNext false)

始终添加最后一个字符

public static String blankWords(String s1) {
    StringBuilder sb = new StringBuilder();
    if(s1.length() > 2) {
      Boolean skipNext = false;
      for(int x = 0; x < s1.length() - 1; x = x + 1) {
        if(s1.charAt(x) == ' ' || s1.charAt(x + 1) == ' ') {
            sb.append(s1.charAt(x));
            skipNext = false;
        }
        else {
            if(skipNext) {
                sb.append('_');
            }
            else {
                sb.append(s1.charAt(x));
                skipNext = true;
            }
        }

      }
      sb.append(s1.charAt(s1.length() - 1));
      return sb.toString();
    }
    return s1;
}
公共静态字符串空白字(字符串s1){
StringBuilder sb=新的StringBuilder();
如果(s1.length()>2){
布尔skipNext=false;
对于(int x=0;x
对于更高级的程序员,请使用正则表达式

public static String blankWords(String s1) {
    return s1.replaceAll("\\B\\w\\B", "_");
}

这正确地保留了最后的
t
,即
空白字(“这是一个测试”)
返回
“t\u s是t\u t”。

这里有一个非常简单的解决方案:

class Scratch {
    public static void main(String[] args) {
        System.out.println(blankWords("My name is sam orozco"));
    }

    public static String delim = "_";

    public static String blankWords(String s1) {
        // this split arg on one or more space
        String[] words = s1.split("\\s+");
        StringBuilder response = new StringBuilder();
        for (String val : words) {
            val = convertWord(val);
            response.append(val).append(" ");
        }
        return response.toString().trim();
    }


    public static String convertWord(String val) {
        int len = val.length();
        StringBuilder bldr = new StringBuilder();
        int index = 0;
        for (char ch : val.toCharArray()) {
            if (index == 0 || index == len - 1) {
                bldr.append(ch);
            } else {
                bldr.append(delim);
            }
            index++;
        }
        return bldr.toString();
    }
}
您可以使用将基于分隔符列表提取单词的。由于您希望在输出中保留这些分隔符,因此将指示标记器将它们作为标记返回:

String blankWords(String s) {
    // build a tokenizer for your string, listing all special chars as delimiters. The last argument says that delimiters are going to be returned as tokens themselves (so we can include them in the output string)
    StringTokenizer tokenizer = new StringTokenizer(s, " .,;:?!()[]{}", true);
    // a helper class to build the output string; think of it as just a more efficient concat utility
    StringBuilder sb = new StringBuilder();
    while (tokenizer.hasMoreTokens()) {
        String blankWord = blank(tokenizer.nextToken());
        sb.append(blankWord);
    }
    return sb.toString();
}

/**
 * Replaces all but the first and last characters in a string with '_'
 */
private String blank(String word) {
    // strings of up to two chars will be returned as such
    // delimiters will always fall into this category, as they are always single characters
    if (word.length() <= 2) {
        return word;
    }
    // no need to iterate through all chars, we'll just get the array
    final char[] chars = word.toCharArray();
    // fill the array of chars with '_', starting with position 1 (the second char) up to the last char (exclusive, i.e. last-but-one)
    Arrays.fill(chars, 1, chars.length - 1, '_');
    // build the resulting word based on the modified array of chars
    return new String(chars);
}
此实现的主要缺点是
StringTokenizer
需要手动列出所有分隔符。通过一个更高级的实现,您可以考虑一个分隔符,该字符返回<代码> false <代码> > <代码>字符。
附言。 正如我前面提到的,这可能是一个“更高级的实现”:

static String blankWords(String text) {
    final char[] textChars = text.toCharArray();
    int wordStart = -1; // keep track of the current word start position, -1 means no current word
    for (int i = 0; i < textChars.length; i++) {
        if (!Character.isAlphabetic(textChars[i])) {
            if (wordStart >= 0) {
                for (int j = wordStart + 1; j < i - 1; j++) {
                    textChars[j] = '_';
                }
            }
            wordStart = -1; // reset the current word to none
        } else if (wordStart == -1) {
            wordStart = i;  // alphabetic characters start a new word, when there's none started already
        } else if (i == textChars.length - 1) { // if the last character is aplhabetic
            for (int j = wordStart + 1; j < i; j++) {
                textChars[j] = '_';
            }
        }
    }
    return new String(textChars);
}
静态字符串空白字(字符串文本){
final char[]textChars=text.tocharray();
int-wordStart=-1;//跟踪当前单词的起始位置,-1表示没有当前单词
for(int i=0;i=0){
对于(intj=wordStart+1;j
这个
虽然(y!=s1.charAt(x))
在程序已经处理最后一个单词的情况下无法工作。没有更多的空格可以退出循环。因此,您需要添加另一个退出条件。您知道StringIndexOutOfBoundsException的含义吗?当您说HW2.blankWords(“这是一个测试”)时,应该输出“T_us是一个T_ut.”,您的意思是包括该句点吗?看起来您的代码没有试图在代码末尾保留句点sentence@Tom我喝醉了。尴尬。你说得太对了。对于输入
“这是一个测试。”
,它返回
“T\uu s是一个T\uuu。”
,但它应该返回
“T\uu s是一个T\uu T。”
——与其测试空格,不如反向检查和测试字母,例如使用
Character.isleter(char ch)
static String blankWords(String text) {
    final char[] textChars = text.toCharArray();
    int wordStart = -1; // keep track of the current word start position, -1 means no current word
    for (int i = 0; i < textChars.length; i++) {
        if (!Character.isAlphabetic(textChars[i])) {
            if (wordStart >= 0) {
                for (int j = wordStart + 1; j < i - 1; j++) {
                    textChars[j] = '_';
                }
            }
            wordStart = -1; // reset the current word to none
        } else if (wordStart == -1) {
            wordStart = i;  // alphabetic characters start a new word, when there's none started already
        } else if (i == textChars.length - 1) { // if the last character is aplhabetic
            for (int j = wordStart + 1; j < i; j++) {
                textChars[j] = '_';
            }
        }
    }
    return new String(textChars);
}