在javascript中返回字符串中的第一个非重复字符 [英] return the first non repeating character in a string in javascript

查看:38
本文介绍了在javascript中返回字符串中的第一个非重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我尝试在搜索中寻找它,但是我能找到的最接近的答案是几种不同语言的相似答案,我想使用Javascript来做到这一点.

So I tried looking for this in the search but the closest I could come is a similar answer in several different languages, I would like to use Javascript to do it.

问题是我有一个任意字符串,我想返回第一个非重复字符.EX:'aba'->将返回b'aabcbd'->将返回c.到目前为止,这就是我所需要的,只是一个简单的for循环开始.

The problem is I have an arbitrary string that I would like to return the first non repeating character. EX: 'aba' -> would return b 'aabcbd' -> would return c. This is what I have so far, just a simple for loop to start.

var someString = 'aabcbd';



var firstNonRepeatedCharacter = function(string) {
for(var i = 0; i < someString.length; i++){

}
};

http://jsfiddle.net/w7F87/不确定从这里去哪里

推荐答案

您可以使用 indexOf 方法来查找非重复字符.如果您在字符串中查找字符,它将是找到的第一个字符,之后将找不到另一个字符:

You can use the indexOf method to find the non repeating character. If you look for the character in the string, it will be the first one found, and you won't find another after it:

function firstNonRepeatedCharacter(string) {
  for (var i = 0; i < string.length; i++) {
    var c = string.charAt(i);
    if (string.indexOf(c) == i && string.indexOf(c, i + 1) == -1) {
      return c;
    }
  }
  return null;
}

演示: http://jsfiddle.net/Guffa/Se4dD/

这篇关于在javascript中返回字符串中的第一个非重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆